#include "iot_i2c.h"
#include "stdint.h"
#include "iot_errno.h"
#include "string.h"
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "los_task.h"
#include "ohos_init.h"
#include "picture.h"
#include "lcd.h"
#include "iot_gpio.h"
#include "los_event.h"
#include "iot_uart.h"
#include "los_queue.h"
#include "los_mux.h"
#include "iot_pwm.h"
#include "iot_adc.h"

/***************************************************************
* 灯光控制状态定义
***************************************************************/
#define LIGHT_STATE_NORMAL          0   // 正常状态
#define LIGHT_STATE_IGNITION_CHANGE 1   // 点火/熄火状态转换中
#define LIGHT_STATE_LOCK_ACTION     2   // 车门锁动作中
#define LIGHT_STATE_ALARM           3   // 报警状态

// 新增云端灯光状态记录
static unsigned int g_headLightCloud = 1;   // 云端下发的大灯状态 (0:关, 1:开)
static unsigned int g_tailLightCloud = 1;   // 云端下发的尾灯状态 (0:关, 1:开)
static unsigned int g_lightRecoveryFlag = 0; // 灯光恢复标志 (0:不需要恢复, 1:需要恢复)
/***************************************************************
* 全局常量定义
***************************************************************/
// ADC按键通道定义
#define KEY_ADC_CHANNEL 7  // 按键对应的ADC通道

// 华为云平台配置
#define DEVICE_ID "684134b3d582f200182e366d_000001" // 设备唯一标识
#define MQTT_TOPIC_PUB "$oc/devices/" DEVICE_ID "/sys/properties/report" // MQTT上报主题
#define SERVICE_ID "qs"  // 云平台服务ID

// 传感器GPIO引脚定义
#define GPIO_Pedestrian      GPIO0_PA3  // 人体检测传感器（1:有人）
#define GPIO_Vibration       GPIO0_PB0  // 震动检测传感器1（0:有发生震动）
#define GPIO_Vibration2      GPIO0_PB1  // 新增震动检测传感器2（0:有发生震动）

// PCF8575引脚定义
#define PCF_LEFT_INFRARED_PIN     0   // 左侧红外检测
#define PCF_RIGHT_INFRARED_PIN    1   // 右侧红外检测
#define PCF_DRIVER_DOOR_PIN       2   // 主驾车门碰撞传感器
#define PCF_PASSENGER_DOOR_PIN    3   // 副驾侧面碰撞传感器
#define PCF_REAR_LEFT_DOOR_PIN    4   // 左侧后车门碰撞传感器
#define PCF_REAR_RIGHT_DOOR_PIN   5   // 右侧后车门碰撞传感器
#define PCF_START_LIGHT_PIN       6   // 启动灯控制（替代点火状态）
#define PCF_HEAD_LIGHT_PIN        7   // 大灯控制
#define PCF_TAIL_LIGHT_PIN        8   // 尾灯控制

/* 蜂鸣器对应PWM */
#define BEEP_PORT EPWMDEV_PWM5_M0
// 电机对应PWM端口
#define ELECTRICAL_MACHINERY_PORT EPWMDEV_PWM6_M0
// 后备箱舵机控制PWM
#define TRUNK_SERVO_PORT EPWMDEV_PWM1_M1

// 系统状态变量
static unsigned int g_carLockStatus = 0;  // 车门锁状态 (1:上锁, 0:解锁)
static unsigned int g_ignitionStatus = 0; // 车辆点火状态 (1:启动, 0:熄火)
static unsigned int g_manualAlarm = 0;    // 手动报警状态 (0:关闭, 1:开启)
static unsigned int g_trunkStatus = 0;    // 后备箱状态 (0:关闭, 1:开启)

// 报警状态变量
static unsigned int g_vibrationAlarm = 0;     // 震动报警状态 (0:无报警, 1:报警)
static unsigned int g_doorAlarm = 0;          // 车门开启报警状态 (0:无报警, 1:报警)
static bool g_shouldReportVibrationAlarm = false;  // 震动报警上报标志
static bool g_shouldReportDoorAlarm = false;       // 车门报警上报标志

// LCD显示的统一报警状态
static unsigned int g_alarmStatus = 0;    // LCD显示报警状态 (0:无报警, 1:报警)

// 风扇状态变量
static unsigned int g_fanSpeed = 0;       // 风扇风速 (0:关闭, 1:低速, 2:中速, 3:高速)

// 灯光控制状态
static unsigned int g_startLight = 0;  // 启动灯状态（替代点火状态）
static unsigned int g_headLight = 0;   // 大灯状态
static unsigned int g_tailLight = 0;   // 尾灯状态

// 传感器原始值存储
static unsigned int Pedestrian_value = 0;   // 人体检测值
static unsigned int Infrared_value = 0;     // 红外检测值
static unsigned int Collide_value = 0;      // 碰撞检测值
static unsigned int Vibration_value = 1;    // 震动检测值
static unsigned int Vibration_value2 = 1;    // 震动检测值
static unsigned int Vibration_count = 0;    // 震动累计计数

// 车门详细状态
static unsigned int g_driver_door = 0;       // 主驾车门状态
static unsigned int g_passenger_door = 0;    // 副驾车门状态
static unsigned int g_rear_left_door = 0;    // 左后车门状态
static unsigned int g_rear_right_door = 0;   // 右后车门状态

// 红外详细状态
static unsigned int g_left_infrared = 0;     // 左侧红外状态
static unsigned int g_right_infrared = 0;    // 右侧红外状态

// 串口配置
#define UART_ID         EUART0_M0        // 串口号
#define STRING_MAXSIZE  256              // 字符串最大长度
#define UART_QUEUE_SIZE 8                // 消息队列容量
#define UART_MSG_SIZE   256              // 单条消息最大长度
#define JSON_BUFFER_SIZE 540             // JSON数据缓冲区大小
#define MAX_JSON_LEN 320
#define MAX_CONTENT_LEN 100

// 事件定义
static EVENT_CB_S m_event;  // 事件控制块
#define EVENT_UART_DATA 0x00000001        // 串口数据事件
#define EVENT_REPORT_SENSORS 0x00000002   // 上报传感器数据事件
#define EVENT_REPORT_ALARM   0x00000004   // 上报报警事件

// 消息队列ID
static UINT32 g_uartQueue;

// 互斥锁定义
static unsigned int g_statusMutex;   // 保护系统状态变量
static unsigned int g_vibMutex;      // 保护震动计数
static unsigned int g_uartMutex;     // 保护串口缓冲区
static unsigned int g_ignitionMutex; // 保护点火状态
static unsigned int g_fanSpeedMutex; // 保护风扇风速的互斥锁
static unsigned int g_manualAlarmMutex;    // 手动报警状态互斥锁
static unsigned int g_vibrationAlarmMutex; // 震动报警状态互斥锁
static unsigned int g_doorAlarmMutex;      // 车门报警状态互斥锁
static unsigned int g_doorDetailMutex;     // 车门详细状态互斥锁
static unsigned int g_infraredDetailMutex; // 红外详细状态互斥锁
static unsigned int g_lightMutex;          // 灯光状态互斥锁
static unsigned int g_trunkMutex;          // 后备箱状态互斥锁

static unsigned char buffer[UART_MSG_SIZE];  // 串口接收缓冲区

// 定位相关全局变量
static char g_latitude[16] = "0.0000";   // GPS纬度（默认值）
static char g_longitude[16] = "0.0000"; // GPS经度（默认值）
static char g_latitude_temp[16] = "0.0000";   // GPS纬度（临时存储）
static char g_longitude_temp[16] = "0.0000"; // GPS经度（临时存储）
static unsigned int g_locationMethod = 0;   // 定位方式(0-GPS 1-基站 2-WiFi)

static unsigned char g_uart_rx_buffer[UART_MSG_SIZE];  // 专用接收缓冲区
static unsigned char g_gps_buffer[UART_MSG_SIZE];      // GPS专用缓冲区

// 温湿度全局变量
static float g_temp = 0.0f;    // 温度值
static float g_humi = 0.0f;    // 湿度值
// LCD显示相关变量
static char g_lcd_message[64] = "系统启动中..."; // LCD显示消息

/***************************************************************
* 灯光控制全局变量
***************************************************************/
static unsigned int g_lightControlState = LIGHT_STATE_NORMAL;
static unsigned int g_headLightNormal = 0;  // 正常状态下的大灯状态
static unsigned int g_tailLightNormal = 0;  // 正常状态下的尾灯状态
static unsigned int g_alarmLightState = 0;   // 报警灯光状态
static unsigned int g_lightActionCounter = 0; // 灯光动作计数器
static unsigned int g_remoteLightCommandLock = 0;  // 远程灯光命令互斥锁
/***************************************************************
* 加速度报警相关变量
***************************************************************/
static short g_accelBaseline[3] = {0};  // 基准加速度值
static unsigned int g_accelAlarm = 0;   // 加速度报警状态 (0:无报警, 1:报警)
static bool g_shouldReportAccelAlarm = false; // 加速度报警上报标志
static unsigned int g_accelAlarmMutex = 0;    // 加速度报警互斥锁

// 修改报警阈值定义（更合理）
#define X_OFFSET_THRESHOLD  300  // X轴偏移阈值 (提高)
#define Y_OFFSET_THRESHOLD  300  // Y轴偏移阈值
#define Z_OFFSET_THRESHOLD  500 // Z轴偏移阈值 (提高)
#define ACCEL_ABS_THRESHOLD 20000 // 绝对加速度阈值 (降低)
static unsigned int g_accelAlarmTimer = 0;    // 加速度报警计时器
const unsigned int ACCEL_ALARM_TIMEOUT = 10;  // 报警超时时间（10*500ms=5秒）

/***************************************************************
* 电子围栏报警相关变量
***************************************************************/
static unsigned int g_fenceAlarm = 0;        // 电子围栏报警状态 (0:未触发, 1:已触发待上报)
static bool g_shouldReportFenceAlarm = false; // 电子围栏报警上报标志
static unsigned int g_fenceAlarmMutex = 0;    // 互斥锁ID
static unsigned int g_fenceAlarmTimer = 0;    // 报警计时器

/***************************************************************
* I2C设备初始化函数 (PCF8575)
***************************************************************/
#define I2C_HANDLE EI2C0_M2
#define SHT30_I2C_ADDRESS 0x44
#define PCF8575_I2C_ADDRESS 0x20  // 假设A0=A1=A2=0
// 全局变量存储当前端口状态
static uint16_t g_current_output = 0xFFFF;  // 初始全高电平
static unsigned int g_pcf8575_mutex = 0;    // 互斥锁ID
/***************************************************************
 * 函数名称: sht30_init
 * 说    明: sht30初始化
 * 参    数: 无
 * 返 回 值: unsigned int IOT_SUCCESS表示成功 IOT_FAILURE表示失败
 ***************************************************************/
static unsigned int sht30_init(void)
{
    unsigned int ret = 0;
    uint8_t send_data[2] = {0x22, 0x36};
    unsigned int send_len = 2;

    ret = IoTI2cWrite(I2C_HANDLE, SHT30_I2C_ADDRESS, send_data, send_len); 
    if (ret != IOT_SUCCESS)
    {
        printf("I2c write failure.\r\n");
        return IOT_FAILURE;
    }

    return IOT_SUCCESS;
}
/***************************************************************
 * pcf8575_init - 初始化PCF8575设备
 * 返回值: IOT_SUCCESS 或 IOT_FAILURE
 ***************************************************************/
unsigned int pcf8575_init(void)
{
    unsigned int ret;
  
    // 创建互斥锁
    if (LOS_MuxCreate(&g_pcf8575_mutex) != LOS_OK) {
        printf("Failed to create PCF8575 mutex\n");
        return IOT_FAILURE;
    }

    // 尝试最多3次初始化
    for (int attempt = 0; attempt < 3; attempt++) {
        uint8_t init_data[2] = {
            (uint8_t)(g_current_output & 0xFF),      // P0端口
            (uint8_t)((g_current_output >> 8) & 0xFF) // P1端口
        };
      
        ret = IoTI2cWrite(I2C_HANDLE, PCF8575_I2C_ADDRESS, init_data, sizeof(init_data));
      
        if (ret == IOT_SUCCESS) {
            printf("PCF8575 init success on attempt %d\n", attempt+1);
            return IOT_SUCCESS;
        }
      
        printf("PCF8575 init failed (attempt %d), error: 0x%X\n", attempt+1, ret);
        LOS_Msleep(20); // 失败后等待20ms
    }
  
    // 终极解决方案：发送软件复位序列
    uint8_t reset_seq[10] = {0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF};
    IoTI2cWrite(I2C_HANDLE, PCF8575_I2C_ADDRESS, reset_seq, sizeof(reset_seq));
    LOS_Msleep(50);
  
    // 最后尝试一次
    uint8_t final_init[2] = {0xFF, 0xFF};
    ret = IoTI2cWrite(I2C_HANDLE, PCF8575_I2C_ADDRESS, final_init, sizeof(final_init));
  
    if (ret == IOT_SUCCESS) {
        g_current_output = 0xFFFF;
        printf("PCF8575 recovered after reset sequence\n");
        return IOT_SUCCESS;
    }
  
    return IOT_FAILURE;
}

/***************************************************************
* 函数名称: sht30_calc_RH
* 说    明: 湿度计算
* 参    数: u16sRH：读取到的湿度原始数据
* 返 回 值: 计算后的湿度数据
***************************************************************/
static float sht30_calc_RH(uint16_t u16sRH)
{
    float humidityRH = 0;

    /*clear bits [1..0] (status bits)*/
    u16sRH &= ~0x0003;
    /*calculate relative humidity [%RH]*/
    /*RH = rawValue / (2^16-1) * 10*/
    humidityRH = (100 * (float)u16sRH / 65535);

    return humidityRH;
}

/***************************************************************
* 函数名称: sht30_calc_temperature
* 说    明: 温度计算
* 参    数: u16sT：读取到的温度原始数据
* 返 回 值: 计算后的温度数据
***************************************************************/
static float sht30_calc_temperature(uint16_t u16sT)
{
    float temperature = 0;

    /*clear bits [1..0] (status bits)*/
    u16sT &= ~0x0003;
    /*calculate temperature [℃]*/
    /*T = -45 + 175 * rawValue / (2^16-1)*/
    temperature = (175 * (float)u16sT / 65535 - 45);

    return temperature;
}

/***************************************************************
* 函数名称: sht30_check_crc
* 说    明: 检查数据正确性
* 参    数: data：读取到的数据
            nbrOfBytes：需要校验的数量
            checksum：读取到的校对比验值
* 返 回 值: 校验结果，0-成功 1-失败
***************************************************************/
static uint8_t sht30_check_crc(uint8_t *data, uint8_t nbrOfBytes, uint8_t checksum)
{
    uint8_t crc = 0xFF;
    uint8_t bit = 0;
    uint8_t byteCtr ;
    const int16_t POLYNOMIAL = 0x131;

    /*calculates 8-Bit checksum with given polynomial*/
    for(byteCtr = 0; byteCtr < nbrOfBytes; ++byteCtr)
    {
        crc ^= (data[byteCtr]);
        for ( bit = 8; bit > 0; --bit)
        {
            if (crc & 0x80) crc = (crc << 1) ^ POLYNOMIAL;
            else crc = (crc << 1);
        }
    }

    if(crc != checksum)
        return 1;
    else
        return 0;
}

/***************************************************************
* 函数名称: sht30_read_data
* 说    明: 读取温度、湿度
* 参    数: temp,humi：读取到的数据,通过指针返回 
* 返 回 值: 无
***************************************************************/
void sht30_read_data(double *temp, double *humi)
{
    /*checksum verification*/
    uint8_t data[3];
    uint16_t tmp;
    uint8_t rc;
    /*byte 0,1 is temperature byte 4,5 is humidity*/
    uint8_t SHT30_Data_Buffer[6];
    memset(SHT30_Data_Buffer, 0, 6);
    uint8_t send_data[2] = {0xE0, 0x00};

    unsigned int send_len = 2;
    IoTI2cWrite(I2C_HANDLE, SHT30_I2C_ADDRESS, send_data, send_len);

    unsigned int receive_len = 6;
    IoTI2cRead(I2C_HANDLE, SHT30_I2C_ADDRESS, SHT30_Data_Buffer, receive_len);

    /*check temperature*/
    data[0] = SHT30_Data_Buffer[0];
    data[1] = SHT30_Data_Buffer[1];
    data[2] = SHT30_Data_Buffer[2];
    rc = sht30_check_crc(data, 2, data[2]);
    if(!rc)
    {
        tmp = ((uint16_t)data[0] << 8) | data[1];
        *temp = sht30_calc_temperature(tmp);
    }
  
    /*check humidity*/
    data[0] = SHT30_Data_Buffer[3];
    data[1] = SHT30_Data_Buffer[4];
    data[2] = SHT30_Data_Buffer[5];
    rc = sht30_check_crc(data, 2, data[2]);
    if(!rc)
    {
        tmp = ((uint16_t)data[0] << 8) | data[1];
        *humi = sht30_calc_RH(tmp);
    }
}


/***************************************************************
 * pcf8575_write - 向PCF8575写入16位数据
 * @data: 16位数据 (P07-P00 和 P17-P10)
 * 返回值: IOT_SUCCESS 或 IOT_FAILURE
 ***************************************************************/
unsigned int pcf8575_write(uint16_t data)
{
    unsigned int ret;
    uint8_t write_data[2] = {
        (uint8_t)(data & 0xFF),      // P0端口
        (uint8_t)((data >> 8) & 0xFF) // P1端口
    };
  
    // 获取互斥锁
    if (LOS_MuxPend(g_pcf8575_mutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return IOT_FAILURE;
    }
  
    // 尝试最多3次写入
    for (int attempt = 0; attempt < 3; attempt++) {
        ret = IoTI2cWrite(I2C_HANDLE, PCF8575_I2C_ADDRESS, write_data, sizeof(write_data));
      
        if (ret == IOT_SUCCESS) {
            g_current_output = data; // 更新缓存状态
            LOS_MuxPost(g_pcf8575_mutex);
            return IOT_SUCCESS;
        }
      
        printf("PCF8575 write failed (attempt %d), error: 0x%X\n", attempt+1, ret);
        LOS_Msleep(5);
    }
  
    LOS_MuxPost(g_pcf8575_mutex);
    return IOT_FAILURE;
}

/***************************************************************
 * pcf8575_read - 从PCF8575读取16位数据
 * @data: 存储读取数据的指针
 * 返回值: IOT_SUCCESS 或 IOT_FAILURE
 ***************************************************************/
unsigned int pcf8575_read(uint16_t *data)
{
    unsigned int ret;
    uint8_t read_data[2] = {0};
  
    // 获取互斥锁
    if (LOS_MuxPend(g_pcf8575_mutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return IOT_FAILURE;
    }
  
    // 尝试最多3次读取
    for (int attempt = 0; attempt < 3; attempt++) {
        ret = IoTI2cRead(I2C_HANDLE, PCF8575_I2C_ADDRESS, read_data, sizeof(read_data));
      
        if (ret == IOT_SUCCESS) {
            *data = (read_data[1] << 8) | read_data[0]; // P1端口 + P0端口
            LOS_MuxPost(g_pcf8575_mutex);
            return IOT_SUCCESS;
        }
      
        printf("PCF8575 read failed (attempt %d), error: 0x%X\n", attempt+1, ret);
        LOS_Msleep(5);
    }
  
    LOS_MuxPost(g_pcf8575_mutex);
    return IOT_FAILURE;
}

/***************************************************************
 * pcf8575_set_pin - 设置单个引脚状态
 * @pin: 引脚编号 (0-15)
 * @state: 0=低电平, 1=高电平
 * 返回值: IOT_SUCCESS 或 IOT_FAILURE
 ***************************************************************/
unsigned int pcf8575_set_pin(uint8_t pin, uint8_t state)
{
    if (pin > 15) return IOT_FAILURE;
  
    // 获取互斥锁
    if (LOS_MuxPend(g_pcf8575_mutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return IOT_FAILURE;
    }
  
    uint16_t new_state = g_current_output;
  
    if (state) {
        new_state |= (1 << pin);  // 设置高电平
    } else {
        new_state &= ~(1 << pin); // 设置低电平
    }
  
    unsigned int ret = pcf8575_write(new_state);
  
    LOS_MuxPost(g_pcf8575_mutex);
    return ret;
}

/***************************************************************
 * pcf8575_get_pin - 读取单个引脚状态
 * @pin: 引脚编号 (0-15)
 * @state: 存储引脚状态的指针
 * 返回值: IOT_SUCCESS 或 IOT_FAILURE
 ***************************************************************/
unsigned int pcf8575_get_pin(uint8_t pin, uint8_t *state)
{
    if (pin > 15) return IOT_FAILURE;
  
    uint16_t port_state;
    if (pcf8575_read(&port_state) != IOT_SUCCESS) {
        return IOT_FAILURE;
    }
  
    *state = (port_state >> pin) & 0x01;
    return IOT_SUCCESS;
}

/***************************************************************
 * pcf8575_set_port - 设置整个端口状态
 * @port0: P0端口状态 (P07-P00)
 * @port1: P1端口状态 (P17-P10)
 * 返回值: IOT_SUCCESS 或 IOT_FAILURE
 ***************************************************************/
unsigned int pcf8575_set_outputs(uint8_t port0, uint8_t port1)
{
    uint16_t data = (port1 << 8) | port0;
    return pcf8575_write(data);
}

/***************************************************************
 * pcf8575_get_inputs - 读取整个端口状态
 * @port0: 存储P0状态的指针
 * @port1: 存储P1状态的指针
 * 返回值: IOT_SUCCESS 或 IOT_FAILURE
 ***************************************************************/
unsigned int pcf8575_get_inputs(uint8_t *port0, uint8_t *port1)
{
    uint16_t data;
    if (pcf8575_read(&data) != IOT_SUCCESS) {
        return IOT_FAILURE;
    }
  
    *port0 = data & 0xFF;
    *port1 = (data >> 8) & 0xFF;
    return IOT_SUCCESS;
}
/***************************************************************
* 函数名称: i2c_dev_init
* 说    明: i2c设备初始化
* 参    数: 无
* 返 回 值: 无
***************************************************************/
void i2c_dev_init(void)
{
    // 初始化I2C总线
    IoTI2cInit(I2C_HANDLE, EI2C_FRE_100K);
   
    // 初始化传感器
    sht30_init();
     LOS_Msleep(50);
     pcf8575_init();
    //pcf8575_set_pin(0,2);
   
 
}
/******************************************
* 修改后的定位解析函数 - 优化基站和WiFi定位处理
******************************************/
void parse_location(char* data, int method) {
    
    // 清空旧数据
    g_latitude[0] = '\0';
    g_longitude[0] = '\0';

    if (method == 0) { // GPS定位
        // 兼容不同前缀的响应
        char* inf_start = strstr(data, "+CGNSINF:");
        if (inf_start) {
            printf("识别到GPS信息");
            // 移动到数据部分: +CGNSINF: <data>
            char* inf_data = inf_start + (inf_start[1] == 'G' ? 10 : 9);
        
            // 分割字段
            char* fields[20];
            int field_count = 0;
            char* token = strtok(inf_data, ",");
        
            while (token && field_count < 20) {
                fields[field_count++] = token;
                token = strtok(NULL, ",");
            }
        
            // 检查字段数量（新响应格式有更多字段）
            if (field_count >= 5) {
                // 检查定位状态（兼容不同字段位置）
                int fixStatus = 0;
                if (field_count >= 5) fixStatus = atoi(fields[1]); // 标准位置
            
                if (fixStatus == 1) {
                    // 修正：纬度在第4字段（索引3），经度在第5字段（索引4）
                    if (field_count >= 5 && strchr(fields[3], '.') && strchr(fields[4], '.')) {
                        strncpy(g_latitude, fields[3], sizeof(g_latitude)-1);
                        strncpy(g_longitude, fields[4], sizeof(g_longitude)-1);
                        strncpy(g_latitude_temp, fields[1],  sizeof(g_latitude_temp)-1);
                        strncpy(g_longitude_temp,fields[2], sizeof(g_longitude_temp)-1);
                        g_locationMethod = 0;
                        return; // 成功解析
                    }
                }
            }
        }
    }
    else if (method == 1) { // 基站定位
        char* loc_start = strstr(data, "+CIPGSMLOC:");
        if (loc_start) {
            char* loc_data = loc_start + strlen("+CIPGSMLOC:");
            // 解析格式: 0,25.890230,114.912422,...
            char* fields[6]; // 增加字段数量
            int field_count = 0;
            char* token = strtok(loc_data, ",");
        
            while (token && field_count < 6) {
                fields[field_count++] = token;
                token = strtok(NULL, ",");
            }
        
            // 至少需要3个字段且定位成功(错误码=0)
            if (field_count >= 3 && atoi(fields[0]) == 0) {
                // 基站定位直接使用返回的坐标值
                strncpy(g_longitude, fields[2], sizeof(g_longitude)-1);
                strncpy(g_latitude, fields[1], sizeof(g_latitude)-1);
                strncpy(g_latitude_temp, fields[1],  sizeof(g_latitude_temp)-1);
                strncpy(g_longitude_temp,fields[2], sizeof(g_longitude_temp)-1);
                printf("基站解析结果: 纬度=%s, 经度=%s\n", g_latitude, g_longitude);
                g_locationMethod = 1;
                return;
            }
        }
    } 
    else if (method == 2) { // WiFi定位
        char* wifi_start = strstr(data, "+WIFILOC:");
        if (wifi_start) {
            char* wifi_data = wifi_start + strlen("+WIFILOC:");
            // 解析格式与基站相同
            char* fields[6];
            int field_count = 0;
            char* token = strtok(wifi_data, ",");
        
            while (token && field_count < 6) {
                fields[field_count++] = token;
                token = strtok(NULL, ",");
            }
        
            if (field_count >= 3 && atoi(fields[0]) == 0) {
                // WiFi定位直接使用返回的坐标值
                strncpy(g_longitude, fields[2], sizeof(g_longitude)-1);
                strncpy(g_latitude, fields[1], sizeof(g_latitude)-1);
                strncpy(g_latitude_temp, fields[1],  sizeof(g_latitude_temp)-1);
                strncpy(g_longitude_temp,fields[2], sizeof(g_longitude_temp)-1);
                printf("WiFi解析结果: 纬度=%s, 经度=%s\n", g_latitude, g_longitude);
                g_locationMethod = 2;
                return;
            }
        }
    }

    // 所有解析失败时设为空
    g_latitude[0] = '\0';
    g_longitude[0] = '\0';
}

bool is_valid_coordinate(const char* lat, const char* lon) {
    if (!lat || !lon) {
        printf("坐标检查: 空指针\n");
        return false;
    }

    if (lat[0] == '\0' || lon[0] == '\0') {
        printf("坐标检查: 空字符串\n");
        return false;
    }

    bool has_dot_lat = (strchr(lat, '.') != NULL);
    bool has_dot_lon = (strchr(lon, '.') != NULL);
    bool valid_length_lat = (strlen(lat) >= 4);
    bool valid_length_lon = (strlen(lon) >= 4);

    printf("坐标检查: lat='%s' (点:%d 长度:%d), lon='%s' (点:%d 长度:%d)\n",
           lat, has_dot_lat, valid_length_lat,
           lon, has_dot_lon, valid_length_lon);

    return has_dot_lat && has_dot_lon && valid_length_lat && valid_length_lon;
}


// 在报警状态更新时设置灯光控制状态
void update_alarm_status()
{
    // 统一报警状态：任意一种报警触发都设置为1
    g_alarmStatus = (g_vibrationAlarm || g_doorAlarm || g_manualAlarm || g_accelAlarm) ? 1 : 0;
    
    // 触发报警灯光状态
    if (g_alarmStatus) {
        g_lightControlState = LIGHT_STATE_ALARM;
        g_lightActionCounter = 0;
    } else {
        g_lightRecoveryFlag = 1;
    }
}

// 辅助函数：安全更新震动报警状态
void update_vibration_alarm_status(unsigned int new_status)
{
    if (LOS_MuxPend(g_vibrationAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    // 检测报警状态变化：从未报警变为报警状态
    if (g_vibrationAlarm == 0 && new_status == 1) {
        g_shouldReportVibrationAlarm = true;  // 设置报警上报标志
    }

    g_vibrationAlarm = new_status;  // 更新状态

    // 更新LCD显示的报警状态
    g_alarmStatus = (g_vibrationAlarm || g_doorAlarm || g_manualAlarm) ? 1 : 0;

    LOS_MuxPost(g_vibrationAlarmMutex);
    update_alarm_status();
}

// 辅助函数：安全获取震动报警状态
unsigned int get_vibration_alarm_status()
{
    unsigned int status;

    if (LOS_MuxPend(g_vibrationAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0; // 默认返回无警报
    }

    status = g_vibrationAlarm;

    LOS_MuxPost(g_vibrationAlarmMutex);
    return status;
}

// 辅助函数：安全更新车门报警状态
void update_door_alarm_status(unsigned int new_status)
{
    if (LOS_MuxPend(g_doorAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    // 检测报警状态变化：从未报警变为报警状态
    if (g_doorAlarm == 0 && new_status == 1) {
        g_shouldReportDoorAlarm = true;  // 设置报警上报标志
    }

    g_doorAlarm = new_status;  // 更新状态

    // 更新LCD显示的报警状态
    g_alarmStatus = (g_vibrationAlarm || g_doorAlarm || g_manualAlarm) ? 1 : 0;

    LOS_MuxPost(g_doorAlarmMutex);
    update_alarm_status();
}

// 辅助函数：安全获取车门报警状态
unsigned int get_door_alarm_status()
{
    unsigned int status;

    if (LOS_MuxPend(g_doorAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0; // 默认返回无警报
    }

    status = g_doorAlarm;

    LOS_MuxPost(g_doorAlarmMutex);
    return status;
}

// 辅助函数：安全获取震动计数
unsigned int get_vibration_count()
{
    unsigned int count;

    if (LOS_MuxPend(g_vibMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0;
    }

    count = Vibration_count;
    LOS_MuxPost(g_vibMutex);
    return count;
}

// 辅助函数：安全增加震动计数
void increment_vibration_count()
{
    if (LOS_MuxPend(g_vibMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    Vibration_count++;
    LOS_MuxPost(g_vibMutex);
}

// 辅助函数：安全重置震动计数
void reset_vibration_count()
{
    if (LOS_MuxPend(g_vibMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    Vibration_count = 0;
    LOS_MuxPost(g_vibMutex);
}

void update_ignition_status(unsigned int new_status)
{
    unsigned int old_status;
    static bool first_time = true;

    if (LOS_MuxPend(g_ignitionMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    old_status = g_ignitionStatus;
    g_ignitionStatus = new_status;

    // 启动灯控制（无论点火状态如何都立即更新）
    pcf8575_set_pin(PCF_START_LIGHT_PIN, !new_status);
    g_startLight = new_status;

    // 点火状态变化的特殊处理
    if (old_status != new_status || first_time) {
        first_time = false;
        
        if (new_status) {
            // 车辆启动：关闭大灯和尾灯（等待云端控制）
            pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);
            pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);
            g_headLight = 0;
            g_tailLight = 0;
            
            // 恢复之前的云端灯光状态
            if (g_lightControlState != LIGHT_STATE_ALARM) {
                pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, !g_headLightCloud);
                pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, !g_tailLightCloud);
                g_headLight = g_headLightCloud;
                g_tailLight = g_tailLightCloud;
            }
            
            // 更新LCD消息
            snprintf(g_lcd_message, sizeof(g_lcd_message), "车辆已启动");
        } else {
            // 车辆熄火：关闭所有灯光
            pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);
            pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);
            g_headLight = 0;
            g_tailLight = 0;
            
            // 记录当前的云端灯光状态用于恢复
            g_headLightCloud = g_headLight;
            g_tailLightCloud = g_tailLight;
            
            // 更新LCD消息
            snprintf(g_lcd_message, sizeof(g_lcd_message), "车辆已熄火");
            
            // 自动关闭风扇
            update_fan_speed(0);
            control_trunk(0);
        }

        // 触发灯光状态转换
        g_lightControlState = LIGHT_STATE_IGNITION_CHANGE;
    }

    LOS_MuxPost(g_ignitionMutex);
}

// 辅助函数：安全获取点火状态
unsigned int get_ignition_status()
{
    unsigned int status;

    if (LOS_MuxPend(g_ignitionMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0; // 默认返回熄火状态
    }

    status = g_ignitionStatus;

    LOS_MuxPost(g_ignitionMutex);
    return status;
}
// 辅助函数：安全更新加速度报警状态
void update_accel_alarm_status(unsigned int new_status)
{
    if (LOS_MuxPend(g_accelAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    // 检测报警状态变化：从未报警变为报警状态
    if (g_accelAlarm == 0 && new_status == 1) {
        g_shouldReportAccelAlarm = true;  // 设置报警上报标志
        g_accelAlarmTimer = 0;            // 重置计时器
    }

    g_accelAlarm = new_status;  // 更新状态

    // 更新统一报警状态
    update_alarm_status();

    LOS_MuxPost(g_accelAlarmMutex);
}

void update_car_lock_status(unsigned int new_status)
{
    unsigned int old_status;
  
    if (LOS_MuxPend(g_statusMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    old_status = g_carLockStatus;
    g_carLockStatus = new_status;

    LOS_MuxPost(g_statusMutex);
  
    // 车门锁状态变化时执行灯光和蜂鸣器动作
    if (old_status != new_status) {
        // 蜂鸣器响一声
        IoTPwmStart(BEEP_PORT, 50, 2000);
        LOS_Msleep(200);
        IoTPwmStop(BEEP_PORT);
      
        // 触发灯光控制状态为锁车动作（除非当前处于报警状态）
        if (g_lightControlState != LIGHT_STATE_ALARM) {
            g_lightControlState = LIGHT_STATE_LOCK_ACTION;
            g_lightActionCounter = 0; // 重置动作计数器
        }
        // 新增：当车门上锁时，记录当前加速度作为基准值
        if (new_status == 1) { // 上锁状态
            short accel_data[3];
            mpu6050_read_data(accel_data); // 读取当前加速度
            g_accelBaseline[0] = accel_data[0];
            g_accelBaseline[1] = accel_data[1];
            g_accelBaseline[2] = accel_data[2];
            printf("记录加速度基准值: x=%d, y=%d, z=%d\n", 
                   g_accelBaseline[0], g_accelBaseline[1], g_accelBaseline[2]);
        }
        
        // 新增：解锁时清除加速度报警
        if (new_status == 0 && g_accelAlarm) {
            update_accel_alarm_status(0);
        }
    }
}
// 辅助函数：安全获取车门锁状态
unsigned int get_car_lock_status()
{
    unsigned int status;

    if (LOS_MuxPend(g_statusMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 1; // 默认返回上锁状态（安全第一）
    }

    status = g_carLockStatus;

    LOS_MuxPost(g_statusMutex);
    return status;
}
/***************************************************************
* 风扇风速控制函数
***************************************************************/
void update_fan_speed(unsigned int new_speed)
{
    // 限制风速范围 (0-3)
    if (new_speed > 3) {
        printf("无效的风扇风速: %d\n", new_speed);
        return;
    }
  
    // 获取互斥锁
    if (LOS_MuxPend(g_fanSpeedMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        printf("获取风扇风速锁失败!\n");
        return;
    }
  
    // 修改点：移除车辆启动状态检查
    // 更新状态
    g_fanSpeed = new_speed;
  
    // 根据风速设置PWM输出
    switch(new_speed) {
        case 0: // 关闭
            IoTPwmStop(ELECTRICAL_MACHINERY_PORT);
            printf("风扇已关闭\n");
            break;
        case 1: // 低速 (25%占空比)
            IoTPwmStart(ELECTRICAL_MACHINERY_PORT, 25, 1000);
            printf("风扇低速运行\n");
            break;
        case 2: // 中速 (50%占空比)
            IoTPwmStart(ELECTRICAL_MACHINERY_PORT, 50, 1000);
            printf("风扇中速运行\n");
            break;
        case 3: // 高速 (75%占空比)
            IoTPwmStart(ELECTRICAL_MACHINERY_PORT, 75, 1000);
            printf("风扇高速运行\n");
            break;
    }
  
    // 释放互斥锁
    LOS_MuxPost(g_fanSpeedMutex);
}
// 安全获取风扇风速
unsigned int get_fan_speed()
{
    unsigned int speed;

    // 获取互斥锁
    if (LOS_MuxPend(g_fanSpeedMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        printf("获取风扇风速锁失败!\n");
        return 0; // 默认返回关闭状态
    }

    speed = g_fanSpeed;

    // 释放互斥锁
    LOS_MuxPost(g_fanSpeedMutex);

    return speed;
}

// 安全更新手动报警状态
void update_manual_alarm(unsigned int new_status)
{
    if (LOS_MuxPend(g_manualAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    g_manualAlarm = new_status;
  
    // 更新LCD显示的报警状态
    g_alarmStatus = (g_vibrationAlarm || g_doorAlarm || g_manualAlarm) ? 1 : 0;
  
    LOS_MuxPost(g_manualAlarmMutex);
    update_alarm_status();
}

// 安全获取手动报警状态
unsigned int get_manual_alarm()
{
    unsigned int status;
    if (LOS_MuxPend(g_manualAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0;
    }
    status = g_manualAlarm;
    LOS_MuxPost(g_manualAlarmMutex);
    return status;
}

// 安全更新车门详细状态
void update_door_detail_status(unsigned int driver, unsigned int passenger, 
                               unsigned int rear_left, unsigned int rear_right)
{
    if (LOS_MuxPend(g_doorDetailMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    g_driver_door = driver;
    g_passenger_door = passenger;
    g_rear_left_door = rear_left;
    g_rear_right_door = rear_right;

    // 任意车门开启即触发碰撞报警
    Collide_value = (driver || passenger || rear_left || rear_right) ? 1 : 0;

    LOS_MuxPost(g_doorDetailMutex);
}

// 安全获取车门详细状态
void get_door_detail_status(unsigned int *driver, unsigned int *passenger, 
                            unsigned int *rear_left, unsigned int *rear_right)
{
    if (LOS_MuxPend(g_doorDetailMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    *driver = g_driver_door;
    *passenger = g_passenger_door;
    *rear_left = g_rear_left_door;
    *rear_right = g_rear_right_door;

    LOS_MuxPost(g_doorDetailMutex);
}

// 安全更新红外详细状态
void update_infrared_detail_status(unsigned int left, unsigned int right)
{
    if (LOS_MuxPend(g_infraredDetailMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    g_left_infrared = left;
    g_right_infrared = right;

    // 任一红外传感器检测到有人（低电平）即触发报警
    Infrared_value = (left == 0 || right == 0) ? 0 : 1;

    LOS_MuxPost(g_infraredDetailMutex);
}

// 安全获取红外详细状态
void get_infrared_detail_status(unsigned int *left, unsigned int *right)
{
    if (LOS_MuxPend(g_infraredDetailMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }

    *left = g_left_infrared;
    *right = g_right_infrared;

    LOS_MuxPost(g_infraredDetailMutex);
}


/***************************************************************
* 灯光控制函数
***************************************************************/
void set_start_light(unsigned int state)
{
    if (LOS_MuxPend(g_lightMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    g_startLight = state;
    pcf8575_set_pin(PCF_START_LIGHT_PIN, state);
    LOS_MuxPost(g_lightMutex);
}

void set_head_light(unsigned int state)
{
    if (LOS_MuxPend(g_lightMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    
    g_headLightCloud = !state; // 状态反转: 云端1=开灯(IO0)
    
    // 仅当正常状态时应用云端命令
    if (g_lightControlState == LIGHT_STATE_NORMAL) {
        pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, state);
        g_headLight = !state;
    }
    
    LOS_MuxPost(g_lightMutex);
}


void set_tail_light(unsigned int state)
{
    if (LOS_MuxPend(g_lightMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    // 记录云端状态
    g_tailLightCloud = !state;//状态反转: 云端1=开灯(IO0)
    
    // 仅当正常状态时应用云端命令
    if (g_lightControlState == LIGHT_STATE_NORMAL) {
        pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, state);
        g_headLight = !state;
    }
    LOS_MuxPost(g_lightMutex);
}

// 安全获取灯光状态
unsigned int get_start_light()
{
    unsigned int state;
    if (LOS_MuxPend(g_lightMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0;
    }
    state = g_startLight;
    LOS_MuxPost(g_lightMutex);
    return state;
}

unsigned int get_head_light()
{
    unsigned int state;
    if (LOS_MuxPend(g_lightMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0;
    }
    state = g_headLight;
    LOS_MuxPost(g_lightMutex);
    return state;
}

unsigned int get_tail_light()
{
    unsigned int state;
    if (LOS_MuxPend(g_lightMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0;
    }
    state = g_tailLight;
    LOS_MuxPost(g_lightMutex);
    return state;
}

/***************************************************************
* 后备箱控制函数
***************************************************************/
void control_trunk(unsigned int state)
{
    // 获取互斥锁
    if (LOS_MuxPend(g_trunkMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    
    // 更新状态
    g_trunkStatus = state;
    
    // 缓慢控制后备箱开关（使用PWM控制舵机）
    if (state) {
         // 缓慢开启后备箱（从0度到180度）
        
        for (int angle = 180; angle >= 0; angle -= 5) {
            int duty = 5 + (angle * 10) / 180; // 15%到5%占空比
            IoTPwmStart(TRUNK_SERVO_PORT, duty, 50); // 50Hz频率
            LOS_Msleep(20); // 每步50ms
        }
        //IoTPwmStart(TRUNK_SERVO_PORT, 5, 50); // 50Hz频率
        printf("后备箱已开启\n");
    } else {
     
         // 缓慢关闭后备箱（从180度到0度）
        for (int angle = 0; angle <= 180; angle += 5) {
            int duty = 5 + (angle * 10) / 180; // 5%到15%占空比
            IoTPwmStart(TRUNK_SERVO_PORT, duty, 50); // 50Hz频率
            LOS_Msleep(20); // 每步50ms
        }
        //oTPwmStart(TRUNK_SERVO_PORT, 15, 50); // 50Hz频率
        printf("后备箱已关闭\n");
    }
    
    // 释放互斥锁
    LOS_MuxPost(g_trunkMutex);
}

// 安全获取后备箱状态
unsigned int get_trunk_status()
{
    unsigned int status;
    if (LOS_MuxPend(g_trunkMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0;
    }
    status = g_trunkStatus;
    LOS_MuxPost(g_trunkMutex);
    return status;
}

/***************************************************************
* 传感器相关函数
***************************************************************/
static unsigned int adc_dev_init()
{
    unsigned int ret = 0;
    ret = IoTAdcInit(KEY_ADC_CHANNEL);
    if(ret != IOT_SUCCESS)
    {
        printf("%s, %s, %d: ADC Init fail\n", __FILE__, __func__, __LINE__);
    }
    return ret;
}

static float adc_get_voltage()
{
    unsigned int ret = IOT_SUCCESS;
    unsigned int data = 0;
    ret = IoTAdcGetVal(KEY_ADC_CHANNEL, &data);
    if (ret != IOT_SUCCESS)
    {
        printf("%s, %s, %d: ADC Read Fail\n", __FILE__, __func__, __LINE__);
        return 0.0;
    }
    return (float)(data * 3.3 / 1024.0);
}

/***************************************************************
* 函数名称: send_mqtt_message
* 功能说明: 通过MQTT协议发送数据到华为云平台
* 参数: 
*   payload - JSON格式的数据负载
*   payload_len - 数据长度
* 注意: 使用分步发送协议（先发主题指令，再发数据）
***************************************************************/
void send_mqtt_message(const char* payload, int payload_len)
{
    // 第一步: 构建并发送AT+MPUBEX指令
    char pub_cmd[128];
    snprintf(pub_cmd, sizeof(pub_cmd), 
             "AT+MPUBEX=%s,0,0,%d\r", 
             MQTT_TOPIC_PUB, payload_len);

    IoTUartWrite(UART_ID, (unsigned char*)pub_cmd, strlen(pub_cmd));
    printf("[MQTT] Sending topic: %s\n", pub_cmd);

    // 给模块处理时间
    LOS_Msleep(100);

    // 第二步: 发送JSON数据
    IoTUartWrite(UART_ID, (unsigned char*)payload, payload_len);
    printf("[MQTT] Sending data: %s\n", payload);

    // 给模块处理时间
    LOS_Msleep(100);
}

/***************************************************************
* 云平台通信函数
***************************************************************/
void report_sensors_to_cloud()
{
    char json_buffer[JSON_BUFFER_SIZE];
    const char* locationType[] = {"Beidou", "BaseStation", "WiFi"};
  
    // 获取详细车门状态
    unsigned int driver_door, passenger_door, rear_left_door, rear_right_door;
    get_door_detail_status(&driver_door, &passenger_door, &rear_left_door, &rear_right_door);
  
    // 获取详细红外状态
    unsigned int left_infrared, right_infrared;
    get_infrared_detail_status(&left_infrared, &right_infrared);
  
    int len = snprintf(json_buffer, sizeof(json_buffer),
    "{\"services\":[{"
    "\"service_id\":\"%s\"," 
    "\"properties\":{" 
    "\"Pedestrian\":%d," 
    "\"LeftInfrared\":%d," 
    "\"RightInfrared\":%d,"
    "\"Infrared\":%d,"
    "\"Alarm\":%d," 
    "\"DriverDoor\":%d," 
    "\"PassengerDoor\":%d," 
    "\"RearLeftDoor\":%d," 
    "\"RearRightDoor\":%d," 
    "\"Vibration\":%d," 
    "\"VibrationCount\":%d," 
    "\"Vibration_alarm\":%d," 
    "\"Door_alarm\":%d," 
    "\"Manual_alarm\":%d," 
    "\"Accel_alarm\":%d," 
    "\"Fence_alarm\":%d,"
    "\"CarLock\":%d," 
    "\"Ignition\":%d," 
    "\"Temperature\":%.1f," 
    "\"Humidity\":%.1f," 
    "\"FanSpeed\":%d," 
    "\"StartLight\":%d," 
    "\"HeadLight\":%d," 
    "\"TailLight\":%d," 
    "\"TrunkStatus\":%d,"  // 新增后备箱状态
    "\"GPS_latitude\":%s," 
    "\"GPS_longitude\":%s," 
    "\"LocationMethod\":\"%s\"" 
    "}}]}", 
    SERVICE_ID,
    Pedestrian_value,
    !left_infrared, 
    !right_infrared,
    Infrared_value,
    g_alarmStatus, 
    driver_door,
    passenger_door,
    rear_left_door,
    rear_right_door,
    !Vibration_value, 
    get_vibration_count(),
    get_vibration_alarm_status(),
    get_door_alarm_status(),
    get_manual_alarm(),  // 新增手动报警状态
    g_accelAlarm,  // 加速度报警状态
    g_fenceAlarm,
    get_car_lock_status(),
    get_ignition_status(),
    g_temp,
    g_humi,
    get_fan_speed(),  // 风扇风速
    get_start_light(),
    get_head_light(),
    get_tail_light(),
    get_trunk_status(), // 后备箱状态
    g_latitude,
    g_longitude,
    locationType[g_locationMethod]);

    if (len > 0 && len < sizeof(json_buffer)) {
        send_mqtt_message(json_buffer, len);
        printf("[周期上报] 传感器数据已上报\n");
    } else {
        printf("JSON数据构造失败! 长度:%d\n", len);
    }
}

void report_vibration_alarm_to_cloud()
{
    char json_buffer[JSON_BUFFER_SIZE];
    const char* locationType[] = {"Beidou", "BaseStation", "WiFi"};
  
    // 获取详细车门状态
    unsigned int driver_door, passenger_door, rear_left_door, rear_right_door;
    get_door_detail_status(&driver_door, &passenger_door, &rear_left_door, &rear_right_door);
  
    // 获取详细红外状态
    unsigned int left_infrared, right_infrared;
    get_infrared_detail_status(&left_infrared, &right_infrared);
  
    int len = snprintf(json_buffer, sizeof(json_buffer),
        "{\"services\":[{" 
        "\"service_id\":\"%s\","
        "\"properties\":{"
        "\"Vibration_alarm\":1," 
        "\"Pedestrian\":%d," 
        "\"LeftInfrared\":%d," 
        "\"RightInfrared\":%d,"
        "\"Infrared\":%d,"
        "\"Alarm\":1,"  
        "\"DriverDoor\":%d," 
        "\"PassengerDoor\":%d," 
        "\"RearLeftDoor\":%d," 
        "\"RearRightDoor\":%d," 
        "\"Vibration\":%d," 
        "\"VibrationCount\":%d," 
        "\"CarLock\":%d," 
        "\"Ignition\":%d," 
        "\"FanSpeed\":%d," 
        "\"StartLight\":%d," 
        "\"HeadLight\":%d," 
        "\"TailLight\":%d," 
        "\"TrunkStatus\":%d,"  // 新增后备箱状态
        "\"GPS_latitude\":%s," 
        "\"GPS_longitude\":%s," 
        "\"LocationMethod\":\"%s\"" 
        "}}]}", 
        SERVICE_ID,
        Pedestrian_value,
        !left_infrared,
        !right_infrared,
        Infrared_value,
        driver_door,
        passenger_door,
        rear_left_door,
        rear_right_door,
        !Vibration_value,
        get_vibration_count(),
        get_car_lock_status(),
        get_ignition_status(),
        get_fan_speed(),  // 风扇风速
        get_start_light(),
        get_head_light(),
        get_tail_light(),
        get_trunk_status(), // 后备箱状态
        g_latitude,
        g_longitude,
        locationType[g_locationMethod]);

    if (len > 0 && len < sizeof(json_buffer)) {
        send_mqtt_message(json_buffer, len);
        printf("[立即上报] 震动报警信息已上报\n");
    
        if (LOS_MuxPend(g_vibrationAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
            return;
        }
        g_shouldReportVibrationAlarm = false;
        LOS_MuxPost(g_vibrationAlarmMutex);
    } else {
        printf("震动报警JSON数据构造失败!\n");
    }
}

void report_door_alarm_to_cloud()
{
    char json_buffer[JSON_BUFFER_SIZE];
    const char* locationType[] = {"Beidou", "BaseStation", "WiFi"};
  
    // 获取详细车门状态
    unsigned int driver_door, passenger_door, rear_left_door, rear_right_door;
    get_door_detail_status(&driver_door, &passenger_door, &rear_left_door, &rear_right_door);
  
    // 获取详细红外状态
    unsigned int left_infrared, right_infrared;
    get_infrared_detail_status(&left_infrared, &right_infrared);
  
    int len = snprintf(json_buffer, sizeof(json_buffer),
        "{\"services\":[{" 
        "\"service_id\":\"%s\","
        "\"properties\":{"
        "\"Door_alarm\":1," 
        "\"Pedestrian\":%d," 
        "\"LeftInfrared\":%d," 
        "\"RightInfrared\":%d,"
        "\"Infrared\":%d,"
        "\"Alarm\":1,"  
        "\"DriverDoor\":%d," 
        "\"PassengerDoor\":%d," 
        "\"RearLeftDoor\":%d," 
        "\"RearRightDoor\":%d," 
        "\"Vibration\":%d," 
        "\"VibrationCount\":%d," 
        "\"CarLock\":%d," 
        "\"Ignition\":%d," 
        "\"FanSpeed\":%d," 
        "\"StartLight\":%d," 
        "\"HeadLight\":%d," 
        "\"TailLight\":%d," 
        "\"TrunkStatus\":%d,"  // 新增后备箱状态
        "\"GPS_latitude\":%s," 
        "\"GPS_longitude\":%s," 
        "\"LocationMethod\":\"%s\"" 
        "}}]}", 
        SERVICE_ID,
        Pedestrian_value,
        !left_infrared,
        !right_infrared,
        Infrared_value,
        driver_door,
        passenger_door,
        rear_left_door,
        rear_right_door,
        !Vibration_value,
        get_vibration_count(),
        get_car_lock_status(),
        get_ignition_status(),
        get_fan_speed(),  // 风扇风速
        get_start_light(),
        get_head_light(),
        get_tail_light(),
        get_trunk_status(), // 后备箱状态
        g_latitude,
        g_longitude,
        locationType[g_locationMethod]);

    if (len > 0 && len < sizeof(json_buffer)) {
        send_mqtt_message(json_buffer, len);
        printf("[立即上报] 车门报警信息已上报\n");
    
        if (LOS_MuxPend(g_doorAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
            return;
        }
        g_shouldReportDoorAlarm = false;
        LOS_MuxPost(g_doorAlarmMutex);
    } else {
        printf("车门报警JSON数据构造失败!\n");
    }
}
// 添加加速度报警上报函数
void report_accel_alarm_to_cloud()
{
    char json_buffer[JSON_BUFFER_SIZE];
    const char* locationType[] = {"Beidou", "BaseStation", "WiFi"};
  
     // 获取详细车门状态
    unsigned int driver_door, passenger_door, rear_left_door, rear_right_door;
    get_door_detail_status(&driver_door, &passenger_door, &rear_left_door, &rear_right_door);
  
    // 获取详细红外状态
    unsigned int left_infrared, right_infrared;
    get_infrared_detail_status(&left_infrared, &right_infrared);
  
    int len = snprintf(json_buffer, sizeof(json_buffer),
        "{\"services\":[{" 
        "\"service_id\":\"%s\","
        "\"properties\":{"
        "\"Accel_alarm\":1,"  // 新增加速度报警字段
        "\"Pedestrian\":%d," 
        "\"LeftInfrared\":%d," 
        "\"RightInfrared\":%d,"
        "\"Infrared\":%d,"
        "\"Alarm\":1,"  
        "\"DriverDoor\":%d," 
        "\"PassengerDoor\":%d," 
        "\"RearLeftDoor\":%d," 
        "\"RearRightDoor\":%d," 
        "\"Vibration\":%d," 
        "\"VibrationCount\":%d," 
        "\"CarLock\":%d," 
        "\"Ignition\":%d," 
        "\"FanSpeed\":%d," 
        "\"StartLight\":%d," 
        "\"HeadLight\":%d," 
        "\"TailLight\":%d," 
        "\"TrunkStatus\":%d," 
        "\"GPS_latitude\":%s," 
        "\"GPS_longitude\":%s," 
        "\"LocationMethod\":\"%s\"" 
        "}}]}", 
        SERVICE_ID,
        Pedestrian_value,
        !left_infrared,
        !right_infrared,
        Infrared_value,
        driver_door,
        passenger_door,
        rear_left_door,
        rear_right_door,
        !Vibration_value,
        get_vibration_count(),
        get_car_lock_status(),
        get_ignition_status(),
        get_fan_speed(),
        get_start_light(),
        get_head_light(),
        get_tail_light(),
        get_trunk_status(),
        g_latitude,
        g_longitude,
        locationType[g_locationMethod]);

    if (len > 0 && len < sizeof(json_buffer)) {
        send_mqtt_message(json_buffer, len);
        printf("[立即上报] 加速度报警信息已上报\n");
        
        // 清除上报标志
        if (LOS_MuxPend(g_accelAlarmMutex, LOS_WAIT_FOREVER) == LOS_OK) {
            g_shouldReportAccelAlarm = false;
            LOS_MuxPost(g_accelAlarmMutex);
        }
    } else {
        printf("加速度报警JSON数据构造失败!\n");
    }
}
// 添加电子围栏报警上报函数
void report_fence_alarm_to_cloud()
{
    char json_buffer[JSON_BUFFER_SIZE];
    const char* locationType[] = {"Beidou", "BaseStation", "WiFi"};
  
    // 获取详细状态
    unsigned int driver_door, passenger_door, rear_left_door, rear_right_door;
    get_door_detail_status(&driver_door, &passenger_door, &rear_left_door, &rear_right_door);
  
    unsigned int left_infrared, right_infrared;
    get_infrared_detail_status(&left_infrared, &right_infrared);
  
    int len = snprintf(json_buffer, sizeof(json_buffer),
        "{\"services\":[{"
        "\"service_id\":\"%s\","
        "\"properties\":{"
        "\"Fence_alarm\":1,"  // 电子围栏报警字段
        "\"Pedestrian\":%d," 
        "\"LeftInfrared\":%d," 
        "\"RightInfrared\":%d,"
        "\"Infrared\":%d,"
        "\"Alarm\":1,"  
        "\"DriverDoor\":%d," 
        "\"PassengerDoor\":%d," 
        "\"RearLeftDoor\":%d," 
        "\"RearRightDoor\":%d," 
        "\"Vibration\":%d," 
        "\"VibrationCount\":%d," 
        "\"CarLock\":%d," 
        "\"Ignition\":%d," 
        "\"FanSpeed\":%d," 
        "\"StartLight\":%d," 
        "\"HeadLight\":%d," 
        "\"TailLight\":%d," 
        "\"TrunkStatus\":%d," 
        "\"GPS_latitude\":%s," 
        "\"GPS_longitude\":%s," 
        "\"LocationMethod\":\"%s\"" 
        "}}]}", 
        SERVICE_ID,
        Pedestrian_value,
        !left_infrared,
        !right_infrared,
        Infrared_value,
        driver_door,
        passenger_door,
        rear_left_door,
        rear_right_door,
        !Vibration_value,
        get_vibration_count(),
        get_car_lock_status(),
        get_ignition_status(),
        get_fan_speed(),
        get_start_light(),
        get_head_light(),
        get_tail_light(),
        get_trunk_status(),
        g_latitude,
        g_longitude,
        locationType[g_locationMethod]);

    if (len > 0 && len < sizeof(json_buffer)) {
        send_mqtt_message(json_buffer, len);
        printf("[立即上报] 电子围栏报警信息已上报\n");
        
        // 清除上报标志
        if (LOS_MuxPend(g_fenceAlarmMutex, LOS_WAIT_FOREVER) == LOS_OK) {
            g_shouldReportFenceAlarm = false;
            LOS_MuxPost(g_fenceAlarmMutex);
        }
        
        // 触发声光提示
        trigger_alarm_ack();
    } else {
        printf("电子围栏报警JSON数据构造失败!\n");
    }
}

// 添加报警成功声光提示函数
void trigger_alarm_ack(void)
{
    // 声光提示：蜂鸣器响0.5秒，灯光闪烁一次
    
    // 灯光闪烁（亮0.25秒，灭0.25秒）
    pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 0);  // 大灯亮
    pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 0);  // 尾灯亮
    
    // 蜂鸣器响
    IoTPwmStart(BEEP_PORT, 50, 2000);  // 50%占空比，2KHz
    LOS_Msleep(250);
    
    pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);  // 大灯灭
    pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);  // 尾灯灭
    LOS_Msleep(250);
    
    // 关闭蜂鸣器
    IoTPwmStop(BEEP_PORT);
    
    printf("电子围栏报警上报成功!\n");
}
/***************************************************************
* 函数名称: parse_cloud_command
* 功能说明: 专用云平台命令解析函数
* 参数: 
*   data - 包含完整云平台命令的字符串
***************************************************************/
void parse_cloud_command(char* data)
{
    printf("检测到云平台下发消息: %s\n", data);
  
    // 查找消息内容部分 - 定位到JSON开始
    char *jsonStart = strchr(data, '{');
    if (!jsonStart) {
        printf("未找到JSON起始位置\n");
        return;
    }
  
    // 查找JSON结束位置
    char *jsonEnd = strrchr(jsonStart, '}');
    if (!jsonEnd) {
        printf("未找到JSON结束位置\n");
        return;
    }
  
    // 计算JSON长度
    int jsonLen = jsonEnd - jsonStart + 1;
  
    // 使用固定大小的缓冲区
    char jsonBuffer[MAX_JSON_LEN];
    int copyLen = (jsonLen < MAX_JSON_LEN - 1) ? jsonLen : MAX_JSON_LEN - 1;
    strncpy(jsonBuffer, jsonStart, copyLen);
    jsonBuffer[copyLen] = '\0';
  
    printf("完整JSON: %s\n", jsonBuffer);
  
    // 解析content字段
    char *contentStart = strstr(jsonBuffer, "\"content\":\"");
    if (!contentStart) {
        printf("未找到content字段\n");
        return;
    }
  
    contentStart += strlen("\"content\":\""); // 移动到内容开始位置
    char *contentEnd = strchr(contentStart, '\"');
    if (!contentEnd) {
        printf("未找到content结束引号\n");
        return;
    }
  
    // 提取content内容
    int contentLen = contentEnd - contentStart;
  
    // 使用固定大小的缓冲区
    char content[MAX_CONTENT_LEN];
    int contentCopyLen = (contentLen < MAX_CONTENT_LEN - 1) ? contentLen : MAX_CONTENT_LEN - 1;
    strncpy(content, contentStart, contentCopyLen);
    content[contentCopyLen] = '\0';
  
    printf("控制命令内容: %s\n", content);
  
    // 解析控制命令
    char *lockCmd = strstr(content, "l:");
    char *ignitionCmd = strstr(content, "i:");
    char *fanCmd = strstr(content, "f:");       // 风扇风速命令
    char *beepCmd = strstr(content, "b:");      // 手动报警命令
    char *headLightCmd = strstr(content, "h:");
    char *tailLightCmd = strstr(content, "t:");
    char *trunkCmd = strstr(content, "k:");     // 后备箱控制命令
    // 1. 车门锁控制
    if (lockCmd) {
        char lockValueChar = lockCmd[2]; // "l:0" 中的 '0'
        if (lockValueChar == '0' || lockValueChar == '1') {
            unsigned int lockValue = lockValueChar - '0';
            update_car_lock_status(lockValue);
            printf("云平台控制 - 车门锁: %d\n", lockValue);
        }
    }
  
    // 2. 点火状态控制
    if (ignitionCmd) {
        char ignitionValueChar = ignitionCmd[2]; // "i:0" 中的 '0'
        if (ignitionValueChar == '0' || ignitionValueChar == '1') {
            unsigned int ignitionValue = ignitionValueChar - '0';
            update_ignition_status(ignitionValue); // 更新点火状态
            printf("云平台控制 - 车辆点火状态: %d\n", ignitionValue);
        }
    }

    // 3. 风扇风速控制 (0-关闭,1-低速,2-中速,3-高速)
    if (fanCmd) {
        char fanValueChar = fanCmd[2]; // "f:2" 中的 '2'
        if (fanValueChar >= '0' && fanValueChar <= '3') {
            unsigned int fanValue = fanValueChar - '0';
          
                update_fan_speed(fanValue);
                printf("云平台控制 - 风扇风速：%d档\n", fanValue);
        
        }
    }
  
    // 4. 手动报警控制
    if (beepCmd) {
        char beepValueChar = beepCmd[2]; // "b:1" 中的 '1'
        if (beepValueChar == '0' || beepValueChar == '1') {
            unsigned int beepValue = beepValueChar - '0';
            update_manual_alarm(beepValue); // 更新手动报警状态
            printf("云平台控制 - 手动报警: %d\n", beepValue);
          
            // 手动报警时更新LCD显示
            if (beepValue) {
                snprintf(g_lcd_message, sizeof(g_lcd_message), "手动报警激活!");
            }
        }
    }
  
    // 5. 大灯控制命令
    if (headLightCmd) {
        char headValueChar = headLightCmd[2]; // "h:0" 中的 '0'
        if (headValueChar == '0' || headValueChar == '1') {
            unsigned int headValue = headValueChar - '0';
            
            // 更新云端状态记录
            g_headLightCloud = !headValue;
            
            // 如果车辆启动，立即应用
            if (get_ignition_status() == 1) {
                pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, !headValue);
                g_headLight = headValue;
            }
            
            printf("云平台控制 - 大灯状态: %d\n", headValue);
        }
    }
  
    // 6. 尾灯控制命令
    if (tailLightCmd) {
        char tailValueChar = tailLightCmd[2]; // "t:0" 中的 '0'
        if (tailValueChar == '0' || tailValueChar == '1') {
            unsigned int tailValue = tailValueChar - '0';
            
            // 更新云端状态记录
            g_tailLightCloud = !tailValue;
            
            // 如果车辆启动，立即应用
            if (get_ignition_status() == 1) {
                pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, !tailValue);
                g_tailLight = tailValue;
            }
            
            printf("云平台控制 - 尾灯状态: %d\n", tailValue);
        }
    }

     // 7. 后备箱控制命令
    if (trunkCmd) {
        char trunkValueChar = trunkCmd[2]; // "k:0" 中的 '0'
        if (trunkValueChar == '0' || trunkValueChar == '1') {
            unsigned int trunkValue = trunkValueChar - '0';
            control_trunk(trunkValue);  // 控制后备箱开关
            printf("云平台控制 - 后备箱: %s\n", 
                   trunkValue ? "开启" : "关闭");
        }
    }
}

/***************************************************************
* 函数名称: uart_recv_task
* 功能说明: 优化版串口接收任务 - 确保云端命令完整接收
***************************************************************/
void uart_recv_task(void)
{
    int len;
    static unsigned char line_buffer[UART_MSG_SIZE];  // 行缓冲区
    static int line_index = 0;                        // 行缓冲区索引
    static unsigned int last_recv_time = 0;           // 最后接收时间

    printf("串口接收任务启动(优化版)...\n");
  
    while (1) {
        unsigned char temp_buffer[UART_MSG_SIZE] = {0};
      
        // 非阻塞读取串口数据
        len = IoTUartRead(UART_ID, temp_buffer, UART_MSG_SIZE - 1);
      
        if (len > 0) {
            // 更新最后接收时间
            last_recv_time = LOS_TickCountGet();
          
            // 处理接收到的每个字节
            for (int i = 0; i < len; i++) {
                // 检查是否行结束(回车或换行)
                if (temp_buffer[i] == '\r' || temp_buffer[i] == '\n') {
                    // 确保行缓冲区以NULL结尾
                    if (line_index < sizeof(line_buffer) - 1) {
                        line_buffer[line_index] = '\0';
                    } else {
                        line_buffer[sizeof(line_buffer) - 1] = '\0';
                    }
                  
                    // 只有非空行才处理
                    if (line_index > 0) {
                        printf("收到完整行: %s\n", line_buffer);
                      
                        // ==== 数据分类处理 ====
                        // 1. 云平台控制命令（最高优先级）
                        if (strstr((char*)line_buffer, "+MSUB:")) {
                            printf(">> 云平台命令分类\n");
                            parse_cloud_command((char*)line_buffer);
                        }
                        // 2. GPS定位数据
                        else if (strstr((char*)line_buffer, "+CGNSINF") || 
                                 strstr((char*)line_buffer, "+CIPGSMLOC") || 
                                 strstr((char*)line_buffer, "+WIFILOC")) {
                            printf(">> GPS数据分类\n");
                            if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
                                // 确保不会溢出
                                size_t copy_len = strlen((char*)line_buffer);
                                if (copy_len >= sizeof(g_gps_buffer)) {
                                    copy_len = sizeof(g_gps_buffer) - 1;
                                }
                                memcpy(g_gps_buffer, line_buffer, copy_len);
                                g_gps_buffer[copy_len] = '\0';
                                LOS_MuxPost(g_uartMutex);
                            }
                        }
                        // 3. 门锁控制命令
                        else if (strstr((char*)line_buffer, "LOCK=")) {
                            printf(">> 门锁控制命令\n");
                            char *lockCmd = strstr((char*)line_buffer, "LOCK=");
                            unsigned int lockValue = 0;
                          
                            if (sscanf(lockCmd + 5, "%u", &lockValue) == 1) {
                                if (lockValue == 0 || lockValue == 1) {
                                    update_car_lock_status(lockValue);
                                    printf("车门锁状态已更新: %d\n", lockValue);
                                  
                                    char response[20];
                                    snprintf(response, sizeof(response), "LOCK_ACK=%d", lockValue);
                                    IoTUartWrite(UART_ID, (unsigned char*)response, strlen(response));
                                } else {
                                    printf("无效的车门锁值: %d\n", lockValue);
                                }
                            }
                        }
                        // 4. 其他未知数据
                        else {
                            printf(">> 未知数据: %s\n", line_buffer);
                        }
                    }
                  
                    // 重置行缓冲区
                    line_index = 0;
                }
                // 普通数据字符
                else {
                    // 确保不超过缓冲区大小
                    if (line_index < sizeof(line_buffer) - 1) {
                        line_buffer[line_index++] = temp_buffer[i];
                    } else {
                        // 缓冲区满，处理当前内容并重置
                        line_buffer[sizeof(line_buffer) - 1] = '\0';
                        printf("行缓冲区满: %s\n", line_buffer);
                        line_index = 0;
                    }
                }
            }
        }
      
        // 命令超时处理（500ms内没有收到新数据）
        if (line_index > 0 && (LOS_TickCountGet() - last_recv_time) > LOS_MS2Tick(2000)) {
            printf("命令超时，处理不完整行: %.*s\n", line_index, line_buffer);
          
            // 处理当前行内容
            line_buffer[line_index] = '\0';
          
            // 尝试处理云平台命令（即使不完整）
            if (strstr((char*)line_buffer, "+MSUB:")) {
                printf(">> 处理不完整云平台命令\n");
                parse_cloud_command((char*)line_buffer);
            }
          
            // 重置行缓冲区
            line_index = 0;
        }
      
        LOS_Msleep(10);  // 10ms轮询间隔
    }
}
/***************************************************************
* 传感器处理任务
***************************************************************/
void gpio_init()
{
    // 初始化GPIO引脚
    IoTGpioInit(GPIO_Pedestrian);
    IoTGpioInit(GPIO_Vibration);
    IoTGpioInit(GPIO_Vibration2);
  
    // 设置GPIO为输入模式
    IoTGpioSetDir(GPIO_Pedestrian, IOT_GPIO_DIR_IN);
    IoTGpioSetDir(GPIO_Vibration, IOT_GPIO_DIR_IN);
    IoTGpioSetDir(GPIO_Vibration2, IOT_GPIO_DIR_IN);
}

void gpio_process()
{
    gpio_init();
     // 震动检测消抖相关变量
    const int DEBOUNCE_SAMPLES = 2;       // 增加消抖采样次数
    const int VIBRATION_THRESHOLD = 1;     // 消抖触发阈值
    static int vibration_samples1 = 0;     // 传感器1采样计数器
    static int vibration_samples2 = 0;     // 传感器2采样计数器
    static bool last_state1 = true;        // 传感器1上次状态（默认高电平）
    static bool last_state2 = true;        // 传感器2上次状态
    static int temp=0;;  
    // 报警状态跟踪变量
    static bool door_alarm_triggered = false;
    static bool vibration_alarm_triggered = false;
    static unsigned int vibration_alarm_timer = 0;
    const unsigned int ALARM_TIMEOUT = 500;  // 50ms*500=25秒
    
    while (1)
    {
        // 读取人体检测传感器
        IoTGpioGetInputVal(GPIO_Pedestrian, &Pedestrian_value);
      
        // ==== 震动传感器消抖处理 ====
        unsigned int raw_val1, raw_val2;
        IoTGpioGetInputVal(GPIO_Vibration, &Vibration_value);
        IoTGpioGetInputVal(GPIO_Vibration2, &Vibration_value2);  // 修正为正确的GPIO
        
        // 传感器1消抖
        vibration_samples1 = (Vibration_value == 0) ? 
            (vibration_samples1 < DEBOUNCE_SAMPLES ? vibration_samples1 + 1 : DEBOUNCE_SAMPLES) :
            (vibration_samples1 > 0 ? vibration_samples1 - 1 : 0);
        
        // 传感器2消抖
        vibration_samples2 = (Vibration_value2 == 0) ? 
            (vibration_samples2 < DEBOUNCE_SAMPLES ? vibration_samples2 + 1 : DEBOUNCE_SAMPLES) :
            (vibration_samples2 > 0 ? vibration_samples2 - 1 : 0);
        
        // 确定有效状态
        bool current_state1 = (vibration_samples1 >= VIBRATION_THRESHOLD);
        bool current_state2 = (vibration_samples2 >= VIBRATION_THRESHOLD);
        
        // 检测震动结束（下降沿）
        if (!current_state1 && last_state1) {
            printf("震动传感器1结束\n");
            increment_vibration_count();
            temp++;
        }
        if (!current_state2 && last_state2) {
            printf("震动传感器2结束\n");
            increment_vibration_count();
            temp++;
        }
        if(temp==2)
        {
            reset_vibration_count();
        }
        last_state1 = current_state1;
        last_state2 = current_state2;
        // ==== 使用PCF8575读取所有传感器 ====
        uint8_t pin_state;
        unsigned int left_infrared, right_infrared;
        unsigned int driver_door, passenger_door, rear_left_door, rear_right_door;
      
        // 读取左侧红外传感器
      
        pcf8575_get_pin(PCF_LEFT_INFRARED_PIN, &pin_state);
        left_infrared = pin_state;
      
        // 读取右侧红外传感器
        pcf8575_get_pin(PCF_RIGHT_INFRARED_PIN, &pin_state);
        right_infrared = pin_state;
      
        // 更新红外详细状态
        update_infrared_detail_status(left_infrared, right_infrared);
      
        // 读取四个车门碰撞传感器
      
        pcf8575_get_pin(PCF_DRIVER_DOOR_PIN, &pin_state);
        driver_door = pin_state;
      
        pcf8575_get_pin(PCF_PASSENGER_DOOR_PIN, &pin_state);
        passenger_door = pin_state;
      
        pcf8575_get_pin(PCF_REAR_LEFT_DOOR_PIN, &pin_state);
        rear_left_door = pin_state;
      
        pcf8575_get_pin(PCF_REAR_RIGHT_DOOR_PIN, &pin_state);
        rear_right_door = pin_state;
      
        // 更新车门详细状态
        update_door_detail_status(driver_door, passenger_door, rear_left_door, rear_right_door);
      
        // 获取车辆锁状态和点火状态
        bool carLocked = (get_car_lock_status() == 1);
        bool ignitionOn = (get_ignition_status() == 1);
        bool doorOpen = (Collide_value == 1);
        bool pedestrianDetected = (Pedestrian_value == 1) || (Infrared_value == 0);

        // 震动报警超时处理
        if (vibration_alarm_triggered) {
            vibration_alarm_timer++;
            if (vibration_alarm_timer >= ALARM_TIMEOUT) {
                printf("震动报警超时，重置震动计数\n");
                reset_vibration_count();
                vibration_alarm_triggered = false;
                vibration_alarm_timer = 0;
                update_vibration_alarm_status(0);
            }
        }

        // 只在车辆熄火且车门上锁时激活异常检测
        if (!ignitionOn && carLocked) {
            bool triggerVibrationAlarm = false;
            bool triggerDoorAlarm = false;
          
            if (doorOpen) {
                if (!door_alarm_triggered) {
                    printf("报警原因: 车门异常开启\n");
                    door_alarm_triggered = true;
                }
                triggerDoorAlarm = true;
                vibration_alarm_timer = 0;
                vibration_alarm_triggered = false;
            } 
            else if (get_vibration_count() >= 3) {
                if (!vibration_alarm_triggered) {
                    printf("报警原因: 震动累计达阈值(%d)\n", get_vibration_count());
                    vibration_alarm_triggered = true;
                    vibration_alarm_timer = 0;
                }
                triggerVibrationAlarm = true;
            }
            else {
                door_alarm_triggered = false;
                if (!vibration_alarm_triggered) {
                    vibration_alarm_triggered = false;
                }
            }
        
            update_door_alarm_status(triggerDoorAlarm ? 1 : 0);
            update_vibration_alarm_status(triggerVibrationAlarm ? 1 : 0);
        } 
        else {
            update_door_alarm_status(0);
            update_vibration_alarm_status(0);
            reset_vibration_count();
            door_alarm_triggered = false;
            vibration_alarm_triggered = false;
            vibration_alarm_timer = 0;
        }

        LOS_Msleep(10);
    }
}
/***************************************************************
* 函数名称: key_scan_task
* 功能说明: ADC按键扫描任务（控制车门锁、点火状态和后备箱）
***************************************************************/
void key_scan_task(void)
{
    float voltage;
    int is_pressed = 0; // 0:未按下 1:按下
    int count = 0;
    int long_press_threshold = 50; // 50 * 100ms = 5秒
    const int LONG_PRESS_THRESHOLD = 50; // 50 * 100ms = 5秒
    static int long_press_counter = 0;   // 长按计数器
    static bool long_press_detected = false; // 防止重复触发
    static float voltage_prev = 0.0f; // 在循环开始前声明
    printf("ADC按键扫描任务启动...\n");

    // 初始化ADC
    if (adc_dev_init() != IOT_SUCCESS) {
        printf("ADC初始化失败!\n");
        return;
    }

    while (1) {
        // 获取ADC电压值
        voltage = adc_get_voltage();
    
        // 检测UP键按下（电压<0.5V）- 切换点火状态
        if ((voltage < 0.5) && (is_pressed == 0)) {
            is_pressed = 1; // 标记按键已按下
            printf("UP键按下\n");
        
            // 切换车辆点火状态（控制启动灯）
            unsigned int currentIgnition = get_ignition_status();
            update_ignition_status(!currentIgnition);
        
            printf("车辆点火状态切换: %s\n", 
                  !currentIgnition ? "启动" : "熄火");
        } 
        // 检测后备箱控制按键（电压在0.5V-1.0V之间）
        else if ((voltage > 0.5) && (voltage < 1.0) && (is_pressed == 0)) {
            is_pressed = 1;
            printf("后备箱控制键按下\n");
            
            // 切换后备箱状态
            control_trunk(!get_trunk_status());
        }
        // 检测DOWN键按下（电压在1.0V-1.5V之间）- 切换车门锁
        else if ((voltage > 1.0) && (voltage < 1.5) && (is_pressed == 0)) {
            is_pressed = 1; // 标记按键已按下
            printf("DOWN键按下\n");
        
            // 切换车门锁状态
            unsigned int currentLock = get_car_lock_status();
            update_car_lock_status(!currentLock);
        
            printf("车门锁状态切换: %s\n", 
                  !currentLock ? "上锁" : "解锁");
        }
        // 检测MID键按下（电压在1.5V-2.5V之间）
        else if ((voltage > 1.5) && (voltage < 2.5)) {
            if (is_pressed == 0) {
                is_pressed = 1;
                long_press_counter = 0;
                long_press_detected = false;
                printf("MID键按下\n");
            }
            
            // 长按检测
            long_press_counter++;
            if (long_press_counter >= LONG_PRESS_THRESHOLD && !long_press_detected) {
                printf("MID键长按5秒 - 触发电子围栏报警!\n");
                
                // 安全更新电子围栏报警状态
                if (LOS_MuxPend(g_fenceAlarmMutex, LOS_WAIT_FOREVER) != LOS_OK) {
                    continue;
                }
                g_fenceAlarm = 1;
                g_shouldReportFenceAlarm = true;
                g_fenceAlarmTimer = 0; // 重置计时器
                LOS_MuxPost(g_fenceAlarmMutex);
                
                long_press_detected = true;
                snprintf(g_lcd_message, sizeof(g_lcd_message), "电子围栏报警已触发!");
            }
        }
        // 按键释放检测（电压>3.2V表示无按键按下）
        else if ((voltage > 3.2) && (is_pressed == 1)) {
            // MID键短按处理（风扇控制）
            if (!long_press_detected && (voltage_prev > 1.5 && voltage_prev < 2.5)) {
                printf("MID键短按 - 切换风扇风速\n");
                
                // 获取当前风扇风速
                unsigned int current_speed = get_fan_speed();
                // 计算下一档风速（0->1->2->3->0循环）
                unsigned int new_speed = (current_speed + 1) % 4;
                
                // 更新风扇风速
                update_fan_speed(new_speed);
                
                // 更新LCD消息
                const char* speed_names[] = {"关闭", "低速", "中速", "高速"};
                snprintf(g_lcd_message, sizeof(g_lcd_message), 
                         "风扇风速: %s", speed_names[new_speed]);
            }
            
            is_pressed = 0; // 标记按键释放
            count = 0;      // 重置长按计数器
            long_press_detected = false; // 重置长按标志
            printf("按键释放\n");
        } 
        // 按键持续按下（长按检测）- 仅对UP键有效
        else if ((voltage < 0.5) && (is_pressed == 1)) {
            count++;
            if (count >= long_press_threshold) {
                printf("长按5秒以上，设备即将重启...\n");
                RebootDevice(3); // 重启设备
            }
        }
        voltage_prev = voltage; // 记录当前电压值供下次比较
        LOS_Msleep(100); // 100ms扫描周期
    }
}
void mpu6050_proress(void *arg)
{
    short mpu6050_data[3] = {0};

    mpu6050_init();
    LOS_Msleep(5000);
    
    while (1) {
        printf("************ Mpu6050 Process ************\n");
        mpu6050_read_data(mpu6050_data);
        printf("x %d y %d z %d \r\n", mpu6050_data[0], mpu6050_data[1], mpu6050_data[2]);

        // 获取车辆状态
        bool carLocked = (get_car_lock_status() == 1);
        bool ignitionOn = (get_ignition_status() == 1);
        
        // 只在车辆锁定且熄火状态检测加速度报警
        if (carLocked && !ignitionOn) {
            // 计算当前加速度与基准值的绝对差
            short diff_x = abs(mpu6050_data[0] - g_accelBaseline[0]);
            short diff_y = abs(mpu6050_data[1] - g_accelBaseline[1]);
            short diff_z = abs(mpu6050_data[2] - g_accelBaseline[2]);
            
            // 检查每个轴的偏移是否超过阈值或者瞬时加速度绝对值是否超过阈值
            bool x_alarm = (diff_x > X_OFFSET_THRESHOLD) || (abs(mpu6050_data[0]) > ACCEL_ABS_THRESHOLD);
            bool y_alarm = (diff_y > Y_OFFSET_THRESHOLD) || (abs(mpu6050_data[1]) > ACCEL_ABS_THRESHOLD);
            bool z_alarm = (diff_z > Z_OFFSET_THRESHOLD) || (abs(mpu6050_data[2]) > ACCEL_ABS_THRESHOLD);
            
            // 任意轴触发报警
            if (x_alarm || y_alarm || z_alarm) {
                    update_accel_alarm_status(1); // 触发加速度报警
                    printf("加速度报警触发！原因:");
                    if (x_alarm) printf(" X轴异常(diff=%d, abs=%d)", diff_x, mpu6050_data[0]);
                    if (y_alarm) printf(" Y轴异常(diff=%d, abs=%d)", diff_y, mpu6050_data[1]);
                    if (z_alarm) printf(" Z轴异常(diff=%d, abs=%d)", diff_z, mpu6050_data[2]);
                    printf("\n");
               
            } else {
                
                // 没有异常时，如果当前处于报警状态，检查是否超时
                if (g_accelAlarm) {
                    g_accelAlarmTimer++;
                    
                    // 报警持续5秒后自动清除
                    if (g_accelAlarmTimer >= ACCEL_ALARM_TIMEOUT) {
                        update_accel_alarm_status(0);
                        printf("加速度报警超时清除\n");
                    }
                }
            }
        } 
        // 车辆未锁定或已启动时强制清除报警
        else if (g_accelAlarm) {
            update_accel_alarm_status(0);
            printf("车辆状态变化，加速度报警清除\n");
        }

        LOS_Msleep(500); // 500ms检测周期
    }
}
/***************************************************************
* 函数名称: uart_send_task
* 功能说明: 串口发送任务（核心数据上报任务） - 优化版本
***************************************************************/
void uart_send_task(void)
{ 
    // 4G模块初始化指令序列
    unsigned char str1_4G[] = "AT\r";
    unsigned char str2_4G[] = "ATE0\r";
    unsigned char str3_4G[] = "AT+ICCID\r";
    unsigned char str4_4G[] = "AT+CGATT?\r";
    unsigned char str5_4G[] = "AT+CSTT=\"\",\"\",\"\" \r";
    unsigned char str6_4G[] = "AT+CIICR\r";
    unsigned char str7_4G[] = "AT+CIFSR\r";

    // MQTT连接指令序列
    unsigned char str1_MQTT[] = "AT+MCONFIG=684134b3d582f200182e366d_000001_0_0_2025060606,684134b3d582f200182e366d_000001,4b4450b0b475e6d56dad6fb3255298912e0667944c3588994249a3e4a0cc1535\r";
    unsigned char str2_MQTT[] = "AT+MIPSTART=7acc11ea0d.st1.iotda-device.cn-north-4.myhuaweicloud.com,1883\r";
    unsigned char str3_MQTT[] = "AT+MCONNECT=1,120\r";
    unsigned char str4_MQTT[] = "AT+MSUB=$oc/devices/684134b3d582f200182e366d_000001/sys/messages/down,1\r";
    unsigned char str5_MQTT[] = "AT+MSUB=t,1\r";

    // GPS定位指令序列
    unsigned char str1_GPS[] = "AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\r";
    unsigned char str2_GPS[] = "AT+SAPBR=3,1,\"APN\",\"\"\r";
    unsigned char str3_GPS[] = "AT+SAPBR=1,1\r";
    unsigned char str4_GPS[] = "AT+SAPBR=2,1\r";
    unsigned char str5_GPS[] = "AT+CGNSPWR=1\r";
    unsigned char str6_GPS[] = "AT+CGNSAID=1,1,1,1\r";

    // 定位相关AT命令
    unsigned char str_GPS[] = "AT+CGNSINF\r";           // GPS查询
    unsigned char str_BaseStation[] = "AT+CIPGSMLOC=1,1\r";  // 基站定位
    unsigned char str_WiFi[] = "AT+WIFILOC=1,1\r";     // WiFi定位

    /****************************************************
    * 第一阶段：通信模块初始化
    ****************************************************/
    printf("\n===== 4G通信模块初始化 =====\n");
    // 建立4G连接
    IoTUartWrite(UART_ID, str1_4G, strlen(str1_4G));
    printf("串口发送: %s\n", str1_4G);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str2_4G, strlen(str2_4G));
    printf("串口发送: %s\n", str2_4G);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str3_4G, strlen(str3_4G));
    printf("串口发送: %s\n", str3_4G);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str4_4G, strlen(str4_4G));
    printf("串口发送: %s\n", str4_4G);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str5_4G, strlen(str5_4G));
    printf("串口发送: %s\n", str5_4G);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str6_4G, strlen(str6_4G));
    printf("串口发送: %s\n", str6_4G);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str7_4G, strlen(str7_4G));
    printf("串口发送: %s\n", str7_4G);
    LOS_Msleep(500);
    printf("4G通讯连接成功！\n");

    printf("\n===== MQTT连接建立 =====\n");
    // 建立MQTT连接
    IoTUartWrite(UART_ID, str1_MQTT, strlen(str1_MQTT));
    printf("串口发送: %s\n", str1_MQTT);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str2_MQTT, strlen(str2_MQTT));
    printf("串口发送: %s\n", str2_MQTT);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str3_MQTT, strlen(str3_MQTT));
    printf("串口发送: %s\n", str3_MQTT);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str4_MQTT, strlen(str4_MQTT));
    printf("串口发送: %s\n", str4_MQTT);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str5_MQTT, strlen(str4_MQTT));
    printf("串口发送: %s\n", str5_MQTT);
    LOS_Msleep(500);
    printf("MQTT服务器连接成功！\n");

    printf("\n===== GPS定位初始化 =====\n");
    // 初始化GPS
    IoTUartWrite(UART_ID, str1_GPS, strlen(str1_GPS));
    printf("串口发送: %s\n", str1_GPS);
    LOS_Msleep(1000);
    IoTUartWrite(UART_ID, str2_GPS, strlen(str2_GPS));
    printf("串口发送: %s\n", str2_GPS);
    LOS_Msleep(1000);
    IoTUartWrite(UART_ID, str3_GPS, strlen(str3_GPS));
    printf("串口发送: %s\n", str3_GPS);
    LOS_Msleep(1000);
    IoTUartWrite(UART_ID, str4_GPS, strlen(str4_GPS));
    printf("串口发送: %s\n", str4_GPS);
    LOS_Msleep(1000);
    IoTUartWrite(UART_ID, str5_GPS, strlen(str5_GPS));
    printf("串口发送: %s\n", str5_GPS);
    LOS_Msleep(1000);
    IoTUartWrite(UART_ID, str6_GPS, strlen(str6_GPS));
    printf("串口发送: %s\n", str6_GPS);
    LOS_Msleep(1000);
    printf("GPS定位连接成功！\n");

    // 获取初始位置（基站定位）
    printf("获取初始位置（基站定位）...\n");
    IoTUartWrite(UART_ID, str_BaseStation, strlen(str_BaseStation));
    LOS_Msleep(2000);  // 等待响应
  
    // 使用专用GPS缓冲区
    if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
        // 注意：这里使用g_gps_buffer而不是全局buffer
        if (g_gps_buffer[0] != '\0') {
            printf("原始基站数据: %s\n", g_gps_buffer);
            parse_location((char*)g_gps_buffer, 1); // 解析基站定位
            memset(g_gps_buffer, 0, sizeof(g_gps_buffer)); // 清空缓冲区
        } else {
            printf("未收到基站定位响应\n");
        }
        LOS_MuxPost(g_uartMutex);
    }
    printf("初始位置: %s, %s\n", g_latitude, g_longitude);
    strncpy(g_latitude_temp, g_latitude, sizeof(g_latitude)-1);
    strncpy(g_longitude_temp, g_longitude, sizeof(g_longitude)-1);

    LOS_Msleep(1500);
    printf("通信模块初始化完成!\n");

    /****************************************************
    * 第二阶段：主循环任务
    ****************************************************/
    // 传感器上报计时器
    unsigned int secondsCounter = 0;       // 秒计数器
    const unsigned int REPORT_INTERVAL = 2; // 1秒上报周期

    // 定位相关变量
    unsigned int GPS_secondsCounter = 0;       // 秒计数器
    const unsigned int GPS_REPORT_INTERVAL = 10; // 10秒获取周期

    printf("进入主监控循环...\n");
    while (1) {
    
        /******************************************
        * 报警检查和上报模块
        ******************************************/
        // 检查是否需要震动报警上报
        bool shouldReportVibrationAlarm = false;
        if (LOS_MuxPend(g_vibrationAlarmMutex, LOS_WAIT_FOREVER) == LOS_OK) {
            shouldReportVibrationAlarm = g_shouldReportVibrationAlarm;
            LOS_MuxPost(g_vibrationAlarmMutex);
        }
    
        // 检查是否需要车门报警上报
        bool shouldReportDoorAlarm = false;
        if (LOS_MuxPend(g_doorAlarmMutex, LOS_WAIT_FOREVER) == LOS_OK) {
            shouldReportDoorAlarm = g_shouldReportDoorAlarm;
            LOS_MuxPost(g_doorAlarmMutex);
        }
        // 新增：检查加速度报警上报
        bool shouldReportAccelAlarm = false;
        if (LOS_MuxPend(g_accelAlarmMutex, LOS_WAIT_FOREVER) == LOS_OK) {
            shouldReportAccelAlarm = g_shouldReportAccelAlarm;
            LOS_MuxPost(g_accelAlarmMutex);
        }
        // 检查是否需要电子围栏报警上报
        bool shouldReportFenceAlarm = false;
        if (LOS_MuxPend(g_fenceAlarmMutex, LOS_WAIT_FOREVER) == LOS_OK) {
            shouldReportFenceAlarm = g_shouldReportFenceAlarm;
            
            // 电子围栏报警计时器逻辑
            if (g_fenceAlarm == 1) {
                g_fenceAlarmTimer++;
                if (g_fenceAlarmTimer >= 5) { // 5秒后自动清零
                    g_fenceAlarm = 0;
                    g_shouldReportFenceAlarm = false;
                    g_fenceAlarmTimer = 0;
                    printf("电子围栏报警5秒后自动清零\n");
                }
            }
            
            LOS_MuxPost(g_fenceAlarmMutex);
        }
        
        // 报警触发时立即上报
        if (shouldReportVibrationAlarm) {
            report_vibration_alarm_to_cloud();  // 紧急上报震动报警
        }
        if (shouldReportDoorAlarm) {
            report_door_alarm_to_cloud();       // 紧急上报车门报警
        }
        if (shouldReportAccelAlarm) {
            report_accel_alarm_to_cloud();      // 紧急上报加速度报警
        }
        // 电子围栏报警触发时立即上报
        if (shouldReportFenceAlarm) {
            report_fence_alarm_to_cloud();
        }
        /******************************************
        * 周期性数据上报
        ******************************************/
        secondsCounter++;
        if (secondsCounter >= REPORT_INTERVAL) {  // 达到上报周期
            report_sensors_to_cloud();  // 周期性上报
            secondsCounter = 0;          // 重置计数器
        }
      
        /******************************************
        * 定位模块 - 优化策略（使用专用GPS缓冲区）
        ******************************************/
        GPS_secondsCounter++;
        if (GPS_secondsCounter >= GPS_REPORT_INTERVAL)
        {
            bool locationSuccess = false;  // 本次定位是否成功
            int currentMethod = 0;         // 当前定位方法
          
            /***** 第一步：尝试GPS定位 *****/
            printf("请求GPS定位...\n");
            g_latitude[0] = '\0';
            g_longitude[0] = '\0';
            currentMethod = 0;
          
            // 清空GPS缓冲区
            if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
                memset(g_gps_buffer, 0, sizeof(g_gps_buffer));
                LOS_MuxPost(g_uartMutex);
            }
          
            // 发送GPS定位请求
            IoTUartWrite(UART_ID, str_GPS, strlen(str_GPS));
            LOS_Msleep(1500);  // 等待响应
          
            // 从专用GPS缓冲区获取数据
            if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
                if (g_gps_buffer[0] != '\0') {
                    printf("原始GPS数据: %s\n", g_gps_buffer);
                    parse_location((char*)g_gps_buffer, currentMethod);
                    memset(g_gps_buffer, 0, sizeof(g_gps_buffer)); // 清空缓冲区
                } else {
                    printf("未收到GPS响应\n");
                }
                LOS_MuxPost(g_uartMutex);
            }
          
            // 检查是否获取到有效坐标
            if (g_locationMethod == 0 && is_valid_coordinate(g_latitude, g_longitude)) {
                locationSuccess = true;
                printf("GPS定位成功\n");
            } else {
                printf("GPS定位失败 - 原因: %s\n", 
                    (g_locationMethod != 0) ? "定位方式错误" : "坐标无效");
            }
        
            /***** 第二步：如果GPS失败，尝试基站定位 *****/
            if (!locationSuccess) {
                printf("尝试基站定位...\n");
                g_latitude[0] = '\0';
                g_longitude[0] = '\0';
                currentMethod = 1;
              
                // 清空GPS缓冲区
                if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
                    memset(g_gps_buffer, 0, sizeof(g_gps_buffer));
                    LOS_MuxPost(g_uartMutex);
                }
              
                // 发送基站定位请求
                IoTUartWrite(UART_ID, str_BaseStation, strlen(str_BaseStation));
                LOS_Msleep(1500);  // 等待响应
              
                // 从专用GPS缓冲区获取数据
                if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
                    if (g_gps_buffer[0] != '\0') {
                        printf("原始基站数据: %s\n", g_gps_buffer);
                        parse_location((char*)g_gps_buffer, currentMethod);
                        memset(g_gps_buffer, 0, sizeof(g_gps_buffer)); // 清空缓冲区
                    } else {
                        printf("未收到基站定位响应\n");
                    }
                    LOS_MuxPost(g_uartMutex);
                }
              
                // 检查基站定位结果
                if (g_locationMethod == 1 && g_latitude[0] != '\0' && g_longitude[0] != '\0') {
                    locationSuccess = true;
                    printf("基站定位成功\n");
                } else {
                    printf("基站定位失败\n");
                }
            }
                    
            /***** 第三步：如果基站失败，尝试WiFi定位 *****/
            if (!locationSuccess) {
                printf("尝试WiFi定位...\n");
                g_latitude[0] = '\0';
                g_longitude[0] = '\0';
                currentMethod = 2;
              
                // 清空GPS缓冲区
                if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
                    memset(g_gps_buffer, 0, sizeof(g_gps_buffer));
                    LOS_MuxPost(g_uartMutex);
                }
              
                // 发送WiFi定位请求
                IoTUartWrite(UART_ID, str_WiFi, strlen(str_WiFi));
                LOS_Msleep(1500);  // 等待响应
              
                // 从专用GPS缓冲区获取数据
                if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) == LOS_OK) {
                    if (g_gps_buffer[0] != '\0') {
                        printf("原始WiFi数据: %s\n", g_gps_buffer);
                        parse_location((char*)g_gps_buffer, currentMethod);
                        memset(g_gps_buffer, 0, sizeof(g_gps_buffer)); // 清空缓冲区
                    } else {
                        printf("未收到WiFi定位响应\n");
                    }
                    LOS_MuxPost(g_uartMutex);
                }
              
                // 检查WiFi定位结果
                if (g_locationMethod == 2 && g_latitude[0] != '\0' && g_longitude[0] != '\0') {
                    locationSuccess = true;
                    printf("WiFi定位成功\n");
                } else {
                    printf("WiFi定位失败\n");
                }
            }
          
            /***** 最终处理 *****/
            if (locationSuccess) {
                // 定位成功，更新临时坐标
                strncpy(g_latitude_temp, g_latitude, sizeof(g_latitude_temp)-1);
                strncpy(g_longitude_temp, g_longitude, sizeof(g_longitude_temp)-1);
            } else {
                // 所有定位方式失败，使用上一次的坐标
                printf("所有定位方式失败，使用上一次坐标\n");
                // 注意：这里不需要更新，所以只是打印
            }
        
            GPS_secondsCounter = 0; // 重置计数器
        }
      
        LOS_Msleep(1000); // 1秒循环一次
    }
}
/***************************************************************
* 函数名称: beep_process
* 说    明: 控制蜂鸣器线程函数（增强版：支持手动报警声光控制）
* 参    数: 无
* 返 回 值: 无
***************************************************************/
void beep_process()
{
    unsigned int ret;
    unsigned int alarmStatus = 0;
    unsigned int manualAlarm = 0;
    unsigned int beepState = 0;  // 蜂鸣器当前状态 (0:关闭, 1:开启)
    unsigned int cycleCounter = 0;
    const unsigned int BEEP_CYCLE = 20; // 100ms * 20 = 2秒周期

    // 初始化蜂鸣器PWM
    ret = IoTPwmInit(BEEP_PORT);
    if (ret != 0) {
        printf("蜂鸣器PWM初始化失败\n");
    }

    while (1)
    {
        alarmStatus = g_alarmStatus;  // 自动报警状态
        manualAlarm = get_manual_alarm(); // 手动报警状态
    
        // 系统报警或手动报警时激活
        if (alarmStatus == 1 || manualAlarm == 1) {
            cycleCounter++;
        
            // 报警周期控制 (1秒开, 1秒关)
            if (cycleCounter <= BEEP_CYCLE/2) {
                // 开启蜂鸣器
                if (!beepState) {
                    ret = IoTPwmStart(BEEP_PORT, 50, 2000); // 50%占空比，2KHz
                    if (ret != 0) printf("蜂鸣器启动失败\n");
                    beepState = 1;
                }
            } else {
                // 关闭蜂鸣器
                if (beepState) {
                    ret = IoTPwmStop(BEEP_PORT);
                    if (ret != 0) printf("蜂鸣器停止失败\n");
                    beepState = 0;
                }
              
                // 重置周期计数器
                if (cycleCounter >= BEEP_CYCLE) {
                    cycleCounter = 0;
                }
            }
        } 
        else {
            // 非报警状态 - 关闭蜂鸣器
            if (beepState) {
                ret = IoTPwmStop(BEEP_PORT);
                set_head_light(1);
                set_tail_light(1);
                if (ret != 0) printf("蜂鸣器停止失败\n");
                beepState = 0;
            }
            cycleCounter = 0;
        }
      
        LOS_Msleep(100); // 100ms控制周期
    }
}
// 温湿度采集任务
void sht30_task(void)
{
    double sht30_data[2] = {0};
    while (1) {
        sht30_read_data(&sht30_data[0], &sht30_data[1]);
    
        // 更新全局变量
        g_temp = sht30_data[0];
        g_humi = sht30_data[1];
    
        LOS_Msleep(2000);  // 2秒采集一次
    }
}

/***************************************************************
* 优化灯光控制任务（修复报警结束问题）
***************************************************************/
void light_control_task(void)
{
    // 1. 初始状态：所有灯光关闭
    pcf8575_set_pin(PCF_START_LIGHT_PIN, 1);  // 启动灯关闭
    pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);   // 大灯关闭
    pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);   // 尾灯关闭
    
    // 状态变量初始化
    g_headLight = 0;
    g_tailLight = 0;
    g_lightRecoveryFlag = 0;
    g_lightControlState = LIGHT_STATE_NORMAL;
    g_lightActionCounter = 0;
    
    printf("灯光控制任务启动(优化版)...\n");
    
    unsigned int blinkCounter = 0;
    const unsigned int BLINK_DURATION = 4; // 250ms * 4 = 1秒闪烁周期
    unsigned int alarmExitFlag = 0; // 新增：报警退出标志
    
    while (1) {
        switch (g_lightControlState) {
            // 正常状态 - 遵循云端控制
            case LIGHT_STATE_NORMAL:
                // 处理灯光恢复标志
                if (g_lightRecoveryFlag) {
                    // 车辆启动时恢复云端灯光
                    if (get_ignition_status()) {
                        g_lightRecoveryFlag = 0; // 立即清除恢复标志
                        pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, !g_headLightCloud);
                        pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, !g_tailLightCloud);
                        g_headLight = g_headLightCloud;
                        g_tailLight = g_tailLightCloud;
                    }
                }
                break;
                
            // 点火/熄火状态转换
            case LIGHT_STATE_IGNITION_CHANGE:
                if (get_ignition_status()) {
                    // 车辆启动：点亮启动灯，关闭其他灯
                    pcf8575_set_pin(PCF_START_LIGHT_PIN, 0);    // 启动灯亮
                    pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);     // 大灯灭
                    pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);     // 尾灯灭
                    g_headLight = 0;
                    g_tailLight = 0;
                } else {
                    // 车辆熄火：关闭所有灯
                    pcf8575_set_pin(PCF_START_LIGHT_PIN, 1);    // 启动灯灭
                    pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);     // 大灯灭
                    pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);     // 尾灯灭
                    g_headLight = 0;
                    g_tailLight = 0;
                    
                    // 清除云端灯光状态
                    g_headLightCloud = 0;
                    g_tailLightCloud = 0;
                }
                g_lightControlState = LIGHT_STATE_NORMAL;
                break;
                
            // 门锁动作 - 灯光闪烁
            case LIGHT_STATE_LOCK_ACTION:
                g_lightActionCounter++;
                
                // 闪烁效果：1Hz频率
                blinkCounter = (blinkCounter + 1) % BLINK_DURATION;
                unsigned int blinkState = (blinkCounter < BLINK_DURATION/2) ? 0 : 1;
                
                // 控制大灯和尾灯闪烁（启动灯不变）
                pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, blinkState);
                pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, blinkState);
                
                // 完成3次完整闪烁后恢复
                if (g_lightActionCounter >= 8) { // 250ms/次 * 12 = 3秒 (3次完整闪烁)
                    // 根据点火状态恢复灯光
                    if (get_ignition_status()) {
                        // 启动状态：维持熄灭
                        pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);
                        pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);
                        g_headLight = 0;
                        g_tailLight = 0;
                    } else {
                        // 熄火状态：所有灯灭
                        pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, 1);
                        pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, 1);
                        g_headLight = 0;
                        g_tailLight = 0;
                    }
                    
                    g_lightControlState = LIGHT_STATE_NORMAL;
                    g_lightActionCounter = 0;
                    blinkCounter = 0;
                }
                break;
                
            // 报警状态 - 灯光闪烁（关键修改部分）
            case LIGHT_STATE_ALARM:
                // 检查是否要退出报警状态
                if (g_alarmStatus == 0 && !alarmExitFlag) {
                    alarmExitFlag = 1; // 设置退出标志但不立即退出
                }
                
                // 正常处理闪烁
                blinkCounter = (blinkCounter + 1) % (BLINK_DURATION/2);
                unsigned int alarmBlinkState = (blinkCounter < BLINK_DURATION/4) ? 0 : 1;
                
                // 控制大灯和尾灯闪烁
                pcf8575_set_pin(PCF_HEAD_LIGHT_PIN, alarmBlinkState);
                pcf8575_set_pin(PCF_TAIL_LIGHT_PIN, alarmBlinkState);
                
                // 处理退出条件：只有在灯灭状态(blinkCounter=0)时才能退出
                if (alarmExitFlag) {
                    if (blinkCounter == 1) {
                        // 确保当前处于熄灭状态
                        g_lightRecoveryFlag = 1;  // 设置恢复标志
                        g_lightControlState = LIGHT_STATE_NORMAL;
                        blinkCounter = 1;
                        alarmExitFlag = 0;  // 清除退出标志
                    }
                }
                break;
        }
        
        LOS_Msleep(250); // 250ms控制周期
    }
}


/***************************************************************
* 函数名称: lcd_process
* 功能说明: LCD显示任务（显示系统状态）
***************************************************************/
void lcd_process(void *arg)
{
    unsigned int cur_sizey = 24;
    char latitude_buffer[16] = {0};
    char longitude_buffer[16] = {0};
    char door_status[16] = {0};
    char infrared_status[8] = {0};
  
    // 获取详细状态
    unsigned int driver_door, passenger_door, rear_left_door, rear_right_door;
    unsigned int left_infrared, right_infrared;

    lcd_init();
    lcd_fill(0, 0, LCD_W, LCD_H, LCD_WHITE);
    printf("LCD任务启动...\n");
  
    lcd_show_chinese(64, 0, "车辆安全监控系统", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(0, 30, "传感器状态", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(120, 30, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(200, 30, "温度", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(248, 30, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(5, 60, "人体检测", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(96, 60, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(160, 60, "红外状态", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(256, 60, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(5, 90, "车门状态", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(96, 90, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(160, 90, "震动检测", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(256, 90, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(0, 120, "车门锁", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(72, 120, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(10, 150, "报警", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(72, 150, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(180, 130, "车辆状态", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(190, 154, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(0, 180, "纬度", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(48, 180, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(0, 210, "经度", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(48, 210, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(180, 186, "定位方式", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(190, 210, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    /*
    lcd_show_chinese(0, 240, "启动灯", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(72, 240, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(100, 240, "大灯", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(148, 240, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(180, 240, "尾灯", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(228, 240, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(100, 270, "风扇", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(148, 270, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    */
    while (1) {
        // 获取详细状态
        get_door_detail_status(&driver_door, &passenger_door, &rear_left_door, &rear_right_door);
        get_infrared_detail_status(&left_infrared, &right_infrared);
      
        // 显示传感器数据
        lcd_show_int_num(125, 60, Pedestrian_value, 1, LCD_RED, LCD_WHITE, 24);
        lcd_show_int_num(280, 90, get_vibration_count(), 2, LCD_RED, LCD_WHITE, 24);
        lcd_show_float_num1(260, 30, g_temp, 4, LCD_RED, LCD_WHITE, 24);
      
        // 显示车门状态详情
        snprintf(door_status, sizeof(door_status), "%d%d%d%d", 
                 driver_door, passenger_door, rear_left_door, rear_right_door);
        lcd_show_string(110, 90, door_status, LCD_RED, LCD_WHITE, 24, 0);
      
      
        // 显示红外状态详情
        snprintf(infrared_status, sizeof(infrared_status), "%d/%d", 
                 !left_infrared, !right_infrared);
        lcd_show_string(280, 60, infrared_status, LCD_RED, LCD_WHITE, 24, 0);
      
        // 显示车门锁状态
        int lockStatus = get_car_lock_status();
        if(lockStatus)
        {
            lcd_show_chinese(96, 120, "已锁定", LCD_RED, LCD_WHITE, 24, 0);
        }
        else{
            lcd_show_chinese(96, 120, "已解锁", LCD_GREEN, LCD_WHITE, 24, 0);
        }
    
        // 显示报警状态
        if(g_alarmStatus)
        {
            lcd_show_chinese(96, 150, "是", LCD_RED, LCD_WHITE, 24, 0);
        }
        else{
            lcd_show_chinese(96, 150, "否", LCD_GREEN, LCD_WHITE, 24, 0);
        }
    
        // 显示车辆状态（点火状态）
        int ignitionStatus = get_ignition_status();
        if(ignitionStatus)
        {
            lcd_show_chinese(200, 154, "已启动", LCD_RED, LCD_WHITE, 24, 0);
        }
        else{
            lcd_show_chinese(200, 154, "已熄火", LCD_GREEN, LCD_WHITE, 24, 0);
        }

        // 显示位置信息
        snprintf(latitude_buffer, sizeof(latitude_buffer), "%s", g_latitude_temp);
        lcd_show_string(62, 180, latitude_buffer, LCD_RED, LCD_WHITE, 24, 0);
        snprintf(longitude_buffer, sizeof(longitude_buffer), "%s", g_longitude_temp);
        lcd_show_string(62, 210, longitude_buffer, LCD_RED, LCD_WHITE, 24, 0);

        // 显示定位方式
        switch(g_locationMethod)
        {
            case 0:lcd_show_chinese(200, 210, "北斗定位 ", LCD_RED, LCD_WHITE, 24, 0);break;
            case 1:lcd_show_chinese(200, 210, "基站定位 ", LCD_RED, LCD_WHITE, 24, 0);break;
            case 2:lcd_show_chinese(200, 210, "WiFi定位 ", LCD_RED, LCD_WHITE, 24, 0);break;
        }
      
/*
        // 显示灯光状态
        lcd_show_int_num(96, 240, get_start_light(), 1, LCD_RED, LCD_WHITE, 24);
        lcd_show_int_num(172, 240, get_head_light(), 1, LCD_RED, LCD_WHITE, 24);
        lcd_show_int_num(252, 240, get_tail_light(), 1, LCD_RED, LCD_WHITE, 24);
      
        // 显示风扇状态
        lcd_show_int_num(172, 270, get_fan_speed(), 1, LCD_RED, LCD_WHITE, 24);
*/
        LOS_Msleep(10);
    }
}

/***************************************************************
* 系统初始化
***************************************************************/
void lcd_example()
{
    unsigned int thread_id;
    TSK_INIT_PARAM_S task = {0};

    if (LOS_EventInit(&m_event) != LOS_OK) {
        printf("事件初始化失败!\n");
        return;
    }

    // 创建互斥锁
    if (LOS_MuxCreate(&g_statusMutex) != LOS_OK) {
        printf("创建状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_vibMutex) != LOS_OK) {
        printf("创建震动计数互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_uartMutex) != LOS_OK) {
        printf("创建串口缓冲区互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_ignitionMutex) != LOS_OK) {
        printf("创建点火状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_fanSpeedMutex) != LOS_OK) {  // 风扇风速互斥锁
        printf("创建风扇风速互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_manualAlarmMutex) != LOS_OK) {
        printf("创建手动报警互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_vibrationAlarmMutex) != LOS_OK) {
        printf("创建震动报警互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_doorAlarmMutex) != LOS_OK) {
        printf("创建车门报警互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_doorDetailMutex) != LOS_OK) {
        printf("创建车门详细状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_infraredDetailMutex) != LOS_OK) {
        printf("创建红外详细状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_lightMutex) != LOS_OK) {
        printf("创建灯光状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_trunkMutex) != LOS_OK) {  // 后备箱状态互斥锁
        printf("创建后备箱状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_accelAlarmMutex) != LOS_OK) {
        printf("创建加速度报警互斥锁失败!\n");
        return;
    }
    // 初始化风扇PWM
    unsigned int ret = IoTPwmInit(ELECTRICAL_MACHINERY_PORT);
    if (ret != 0) {
        printf("风扇PWM初始化失败(%d)\n", ELECTRICAL_MACHINERY_PORT);
    }
  
    // 初始化后备箱舵机PWM
    ret = IoTPwmInit(TRUNK_SERVO_PORT);
    if (ret != 0) {
        printf("后备箱舵机PWM初始化失败(%d)\n", TRUNK_SERVO_PORT);
    }
  
    // 创建电子围栏报警互斥锁
    if (LOS_MuxCreate(&g_fenceAlarmMutex) != LOS_OK) {
        printf("创建电子围栏报警互斥锁失败!\n");
        return;
    }
    // 串口配置参数
    IotUartAttribute attr = {
        .baudRate = 115200,
        .dataBits = IOT_UART_DATA_BIT_8,
        .pad = IOT_FLOW_CTRL_NONE,
        .parity = IOT_UART_PARITY_NONE,
        .rxBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK,
        .stopBits = IOT_UART_STOP_BIT_1,
        .txBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK
    };

    if (IoTUartInit(UART_ID, &attr) != IOT_SUCCESS) {
        printf("串口初始化失败!\n");
        return;
    }
    printf("串口初始化成功！\n");
    i2c_dev_init();
    // 初始状态设置
    control_trunk(0);
    // 初始化加速度报警状态
    g_accelAlarm = 0;
    g_shouldReportAccelAlarm = false;
    update_car_lock_status(1);
    update_ignition_status(0);
    update_manual_alarm(0);  // 手动报警关闭
    reset_vibration_count();
    g_shouldReportVibrationAlarm = false;
    g_shouldReportDoorAlarm = false;
    memset(g_gps_buffer, 0, sizeof(g_gps_buffer));
  
    // 初始化详细状态
    update_door_detail_status(0, 0, 0, 0);
    update_infrared_detail_status(0, 0);
    if (LOS_QueueCreate("uart_queue", 
                      UART_QUEUE_SIZE, 
                      &g_uartQueue, 
                      0, 
                      UART_MSG_SIZE) != LOS_OK) {
        printf("创建串口消息队列失败!\n");
        return;
    }

    // LCD显示任务
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)lcd_process;
    task.uwStackSize = 4096;
    task.pcName = "lcd_task";
    task.usTaskPrio = 27;
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建LCD任务失败!\n");
        return;
    }
  
    // GPIO传感器采集任务
    task.pfnTaskEntry = gpio_process;
    task.uwStackSize = 2048;
    task.pcName = "gpio_task";
    task.usTaskPrio = 26;
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建GPIO任务失败!\n");
        return;
    }
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)mpu6050_proress;
    task.uwStackSize = 2048;
    task.pcName = "mpu6050 process";
    task.usTaskPrio = 25;
    ret = LOS_TaskCreate(&thread_id, &task);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }
    // 串口发送任务
    task.pfnTaskEntry = uart_send_task;
    task.uwStackSize = 3072;
    task.pcName = "uart_send_task";
    task.usTaskPrio = 24;
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建串口发送任务失败!\n");
        return;
    }

    // 串口接收任务
    task.pfnTaskEntry = uart_recv_task;
    task.uwStackSize = 3072;
    task.pcName = "uart_recv_task";
    task.usTaskPrio = 23;
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建串口接收任务失败!\n");
        return;
    }
  
    // 按键扫描任务
    task.pfnTaskEntry = key_scan_task;
    task.uwStackSize = 2048;
    task.pcName = "key_scan_task";
    task.usTaskPrio = 22;
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建按键扫描任务失败!\n");
        return;
    }
  
    // 温湿度采集任务
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)sht30_task;
    task.uwStackSize = 2048;
    task.pcName = "sht30_task";
    task.usTaskPrio = 21;
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建温湿度任务失败!\n");
        return;
    }
  
    // 蜂鸣器任务
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)beep_process;
    task.uwStackSize = 2048;
    task.pcName = "beep_process";
    task.usTaskPrio = 20;
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建蜂鸣器任务失败!\n");
        return;
    }

    // 灯光控制任务
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)light_control_task;
    task.uwStackSize = 2048;
    task.pcName = "light_control_task";
    task.usTaskPrio = 19;  // 较高优先级
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建灯光控制任务失败!\n");
        return;
    }
   
    printf("系统任务已全部创建!\n");
}

APP_FEATURE_INIT(lcd_example);